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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1347  ! raeburn     4: # $Id: loncommon.pm,v 1.1346 2020/09/22 12:19:15 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 {
                   1419:     my ($text) = @_;
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.1159    raeburn  1433: <a href="$link" title="$title">$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.112     bowersj2 4896: =pod
                   4897: 
1.648     raeburn  4898: =item * &get_student_answers() 
1.112     bowersj2 4899: 
                   4900: show a snapshot of how student was answering problem
                   4901: 
                   4902: =cut
                   4903: 
1.11      albertel 4904: sub get_student_answers {
1.100     sakharuk 4905:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4906:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4907:   my (%moreenv);
1.11      albertel 4908:   my @elements=('symb','courseid','domain','username');
                   4909:   foreach my $element (@elements) {
1.186     albertel 4910:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4911:   }
1.186     albertel 4912:   $moreenv{'grade_target'}='answer';
                   4913:   %moreenv=(%form,%moreenv);
1.497     raeburn  4914:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4915:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4916:   return $userview;
1.1       albertel 4917: }
1.116     albertel 4918: 
                   4919: =pod
                   4920: 
                   4921: =item * &submlink()
                   4922: 
1.242     albertel 4923: Inputs: $text $uname $udom $symb $target
1.116     albertel 4924: 
                   4925: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4926: 
                   4927: =cut
                   4928: 
                   4929: ###############################################
                   4930: sub submlink {
1.242     albertel 4931:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4932:     if (!($uname && $udom)) {
                   4933: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4934: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4935: 	if (!$symb) { $symb=$cursymb; }
                   4936:     }
1.254     matthew  4937:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4938:     $symb=&escape($symb);
1.960     bisitz   4939:     if ($target) { $target=" target=\"$target\""; }
                   4940:     return
                   4941:         '<a href="/adm/grades?command=submission'.
                   4942:         '&amp;symb='.$symb.
                   4943:         '&amp;student='.$uname.
                   4944:         '&amp;userdom='.$udom.'"'.
                   4945:         $target.'>'.$text.'</a>';
1.242     albertel 4946: }
                   4947: ##############################################
                   4948: 
                   4949: =pod
                   4950: 
                   4951: =item * &pgrdlink()
                   4952: 
                   4953: Inputs: $text $uname $udom $symb $target
                   4954: 
                   4955: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4956: 
                   4957: =cut
                   4958: 
                   4959: ###############################################
                   4960: sub pgrdlink {
                   4961:     my $link=&submlink(@_);
                   4962:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4963:     return $link;
                   4964: }
                   4965: ##############################################
                   4966: 
                   4967: =pod
                   4968: 
                   4969: =item * &pprmlink()
                   4970: 
                   4971: Inputs: $text $uname $udom $symb $target
                   4972: 
                   4973: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4974: student and a specific resource
1.242     albertel 4975: 
                   4976: =cut
                   4977: 
                   4978: ###############################################
                   4979: sub pprmlink {
                   4980:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4981:     if (!($uname && $udom)) {
                   4982: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4983: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4984: 	if (!$symb) { $symb=$cursymb; }
                   4985:     }
1.254     matthew  4986:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4987:     $symb=&escape($symb);
1.242     albertel 4988:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4989:     return '<a href="/adm/parmset?command=set&amp;'.
                   4990: 	'symb='.$symb.'&amp;uname='.$uname.
                   4991: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4992: }
                   4993: ##############################################
1.37      matthew  4994: 
1.112     bowersj2 4995: =pod
                   4996: 
                   4997: =back
                   4998: 
                   4999: =cut
                   5000: 
1.37      matthew  5001: ###############################################
1.51      www      5002: 
                   5003: 
                   5004: sub timehash {
1.687     raeburn  5005:     my ($thistime) = @_;
                   5006:     my $timezone = &Apache::lonlocal::gettimezone();
                   5007:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5008:                      ->set_time_zone($timezone);
                   5009:     my $wday = $dt->day_of_week();
                   5010:     if ($wday == 7) { $wday = 0; }
                   5011:     return ( 'second' => $dt->second(),
                   5012:              'minute' => $dt->minute(),
                   5013:              'hour'   => $dt->hour(),
                   5014:              'day'     => $dt->day_of_month(),
                   5015:              'month'   => $dt->month(),
                   5016:              'year'    => $dt->year(),
                   5017:              'weekday' => $wday,
                   5018:              'dayyear' => $dt->day_of_year(),
                   5019:              'dlsav'   => $dt->is_dst() );
1.51      www      5020: }
                   5021: 
1.370     www      5022: sub utc_string {
                   5023:     my ($date)=@_;
1.371     www      5024:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5025: }
                   5026: 
1.51      www      5027: sub maketime {
                   5028:     my %th=@_;
1.687     raeburn  5029:     my ($epoch_time,$timezone,$dt);
                   5030:     $timezone = &Apache::lonlocal::gettimezone();
                   5031:     eval {
                   5032:         $dt = DateTime->new( year   => $th{'year'},
                   5033:                              month  => $th{'month'},
                   5034:                              day    => $th{'day'},
                   5035:                              hour   => $th{'hour'},
                   5036:                              minute => $th{'minute'},
                   5037:                              second => $th{'second'},
                   5038:                              time_zone => $timezone,
                   5039:                          );
                   5040:     };
                   5041:     if (!$@) {
                   5042:         $epoch_time = $dt->epoch;
                   5043:         if ($epoch_time) {
                   5044:             return $epoch_time;
                   5045:         }
                   5046:     }
1.51      www      5047:     return POSIX::mktime(
                   5048:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5049:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5050: }
                   5051: 
                   5052: #########################################
1.51      www      5053: 
                   5054: sub findallcourses {
1.482     raeburn  5055:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5056:     my %roles;
                   5057:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5058:     my %courses;
1.51      www      5059:     my $now=time;
1.482     raeburn  5060:     if (!defined($uname)) {
                   5061:         $uname = $env{'user.name'};
                   5062:     }
                   5063:     if (!defined($udom)) {
                   5064:         $udom = $env{'user.domain'};
                   5065:     }
                   5066:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5067:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5068:         if (!%roles) {
                   5069:             %roles = (
                   5070:                        cc => 1,
1.907     raeburn  5071:                        co => 1,
1.482     raeburn  5072:                        in => 1,
                   5073:                        ep => 1,
                   5074:                        ta => 1,
                   5075:                        cr => 1,
                   5076:                        st => 1,
                   5077:              );
                   5078:         }
                   5079:         foreach my $entry (keys(%roleshash)) {
                   5080:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5081:             if ($trole =~ /^cr/) { 
                   5082:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5083:             } else {
                   5084:                 next if (!exists($roles{$trole}));
                   5085:             }
                   5086:             if ($tend) {
                   5087:                 next if ($tend < $now);
                   5088:             }
                   5089:             if ($tstart) {
                   5090:                 next if ($tstart > $now);
                   5091:             }
1.1058    raeburn  5092:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5093:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5094:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5095:             if ($secpart eq '') {
                   5096:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5097:                 $sec = 'none';
1.1058    raeburn  5098:                 $value .= $cnum.'/';
1.482     raeburn  5099:             } else {
                   5100:                 $cnum = $cnumpart;
                   5101:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5102:                 $value .= $cnum.'/'.$sec;
                   5103:             }
                   5104:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5105:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5106:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5107:                 }
                   5108:             } else {
                   5109:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5110:             }
1.482     raeburn  5111:         }
                   5112:     } else {
                   5113:         foreach my $key (keys(%env)) {
1.483     albertel 5114: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5115:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5116: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5117: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5118: 	        next if (%roles && !exists($roles{$role}));
                   5119: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5120:                 my $active=1;
                   5121:                 if ($starttime) {
                   5122: 		    if ($now<$starttime) { $active=0; }
                   5123:                 }
                   5124:                 if ($endtime) {
                   5125:                     if ($now>$endtime) { $active=0; }
                   5126:                 }
                   5127:                 if ($active) {
1.1058    raeburn  5128:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5129:                     if ($sec eq '') {
                   5130:                         $sec = 'none';
1.1058    raeburn  5131:                     } else {
                   5132:                         $value .= $sec;
                   5133:                     }
                   5134:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5135:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5136:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5137:                         }
                   5138:                     } else {
                   5139:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5140:                     }
1.474     raeburn  5141:                 }
                   5142:             }
1.51      www      5143:         }
                   5144:     }
1.474     raeburn  5145:     return %courses;
1.51      www      5146: }
1.37      matthew  5147: 
1.54      www      5148: ###############################################
1.474     raeburn  5149: 
                   5150: sub blockcheck {
1.1347  ! raeburn  5151:     my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  5152: 
1.1189    raeburn  5153:     if (defined($udom) && defined($uname)) {
                   5154:         # If uname and udom are for a course, check for blocks in the course.
                   5155:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5156:             my ($startblock,$endblock,$triggerblock) =
1.1347  ! raeburn  5157:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5158:             return ($startblock,$endblock,$triggerblock);
                   5159:         }
                   5160:     } else {
1.490     raeburn  5161:         $udom = $env{'user.domain'};
                   5162:         $uname = $env{'user.name'};
                   5163:     }
                   5164: 
1.502     raeburn  5165:     my $startblock = 0;
                   5166:     my $endblock = 0;
1.1062    raeburn  5167:     my $triggerblock = '';
1.482     raeburn  5168:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5169: 
1.490     raeburn  5170:     # If uname is for a user, and activity is course-specific, i.e.,
                   5171:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5172: 
1.490     raeburn  5173:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5174:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5175:          $activity eq 'search' || $activity eq 'reinit' ||
                   5176:          $activity eq 'alert') &&
1.1189    raeburn  5177:         ($env{'request.course.id'})) {
1.490     raeburn  5178:         foreach my $key (keys(%live_courses)) {
                   5179:             if ($key ne $env{'request.course.id'}) {
                   5180:                 delete($live_courses{$key});
                   5181:             }
                   5182:         }
                   5183:     }
                   5184: 
                   5185:     my $otheruser = 0;
                   5186:     my %own_courses;
                   5187:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5188:         # Resource belongs to user other than current user.
                   5189:         $otheruser = 1;
                   5190:         # Gather courses for current user
                   5191:         %own_courses = 
                   5192:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5193:     }
                   5194: 
                   5195:     # Gather active course roles - course coordinator, instructor, 
                   5196:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5197: 
                   5198:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5199:         my ($cdom,$cnum);
                   5200:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5201:             $cdom = $env{'course.'.$course.'.domain'};
                   5202:             $cnum = $env{'course.'.$course.'.num'};
                   5203:         } else {
1.490     raeburn  5204:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5205:         }
                   5206:         my $no_ownblock = 0;
                   5207:         my $no_userblock = 0;
1.533     raeburn  5208:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5209:             # Check if current user has 'evb' priv for this
                   5210:             if (defined($own_courses{$course})) {
                   5211:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5212:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5213:                     if ($sec ne 'none') {
                   5214:                         $checkrole .= '/'.$sec;
                   5215:                     }
                   5216:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5217:                         $no_ownblock = 1;
                   5218:                         last;
                   5219:                     }
                   5220:                 }
                   5221:             }
                   5222:             # if they have 'evb' priv and are currently not playing student
                   5223:             next if (($no_ownblock) &&
                   5224:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5225:         }
1.474     raeburn  5226:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5227:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5228:             if ($sec ne 'none') {
1.482     raeburn  5229:                 $checkrole .= '/'.$sec;
1.474     raeburn  5230:             }
1.490     raeburn  5231:             if ($otheruser) {
                   5232:                 # Resource belongs to user other than current user.
                   5233:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5234:                 my (%allroles,%userroles);
                   5235:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5236:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5237:                         my ($trole,$tdom,$tnum,$tsec);
                   5238:                         if ($entry =~ /^cr/) {
                   5239:                             ($trole,$tdom,$tnum,$tsec) = 
                   5240:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5241:                         } else {
                   5242:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5243:                         }
                   5244:                         my ($spec,$area,$trest);
                   5245:                         $area = '/'.$tdom.'/'.$tnum;
                   5246:                         $trest = $tnum;
                   5247:                         if ($tsec ne '') {
                   5248:                             $area .= '/'.$tsec;
                   5249:                             $trest .= '/'.$tsec;
                   5250:                         }
                   5251:                         $spec = $trole.'.'.$area;
                   5252:                         if ($trole =~ /^cr/) {
                   5253:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5254:                                                               $tdom,$spec,$trest,$area);
                   5255:                         } else {
                   5256:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5257:                                                                 $tdom,$spec,$trest,$area);
                   5258:                         }
                   5259:                     }
1.1276    raeburn  5260:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5261:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5262:                         if ($1) {
                   5263:                             $no_userblock = 1;
                   5264:                             last;
                   5265:                         }
1.486     raeburn  5266:                     }
                   5267:                 }
1.490     raeburn  5268:             } else {
                   5269:                 # Resource belongs to current user
                   5270:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5271:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5272:                     $no_ownblock = 1;
                   5273:                     last;
                   5274:                 }
1.474     raeburn  5275:             }
                   5276:         }
                   5277:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5278:         next if (($no_ownblock) &&
1.491     albertel 5279:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5280:         next if ($no_userblock);
1.474     raeburn  5281: 
1.1303    raeburn  5282:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5283:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5284: 
1.1062    raeburn  5285:         my ($start,$end,$trigger) = 
1.1347  ! raeburn  5286:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5287:         if (($start != 0) && 
                   5288:             (($startblock == 0) || ($startblock > $start))) {
                   5289:             $startblock = $start;
1.1062    raeburn  5290:             if ($trigger ne '') {
                   5291:                 $triggerblock = $trigger;
                   5292:             }
1.502     raeburn  5293:         }
                   5294:         if (($end != 0)  &&
                   5295:             (($endblock == 0) || ($endblock < $end))) {
                   5296:             $endblock = $end;
1.1062    raeburn  5297:             if ($trigger ne '') {
                   5298:                 $triggerblock = $trigger;
                   5299:             }
1.502     raeburn  5300:         }
1.490     raeburn  5301:     }
1.1062    raeburn  5302:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5303: }
                   5304: 
                   5305: sub get_blocks {
1.1347  ! raeburn  5306:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5307:     my $startblock = 0;
                   5308:     my $endblock = 0;
1.1062    raeburn  5309:     my $triggerblock = '';
1.490     raeburn  5310:     my $course = $cdom.'_'.$cnum;
                   5311:     $setters->{$course} = {};
                   5312:     $setters->{$course}{'staff'} = [];
                   5313:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5314:     $setters->{$course}{'triggers'} = [];
                   5315:     my (@blockers,%triggered);
                   5316:     my $now = time;
                   5317:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5318:     if ($activity eq 'docs') {
1.1347  ! raeburn  5319:         my ($blocked,$nosymbcache);
        !          5320:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
        !          5321:             $blocked = 1;
        !          5322:             $nosymbcache = 1;
        !          5323:         }
        !          5324:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$blocked,\%commblocks);
1.1062    raeburn  5325:         foreach my $block (@blockers) {
                   5326:             if ($block =~ /^firstaccess____(.+)$/) {
                   5327:                 my $item = $1;
                   5328:                 my $type = 'map';
                   5329:                 my $timersymb = $item;
                   5330:                 if ($item eq 'course') {
                   5331:                     $type = 'course';
                   5332:                 } elsif ($item =~ /___\d+___/) {
                   5333:                     $type = 'resource';
                   5334:                 } else {
                   5335:                     $timersymb = &Apache::lonnet::symbread($item);
                   5336:                 }
                   5337:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5338:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5339:                 $triggered{$block} = {
                   5340:                                        start => $start,
                   5341:                                        end   => $end,
                   5342:                                        type  => $type,
                   5343:                                      };
                   5344:             }
                   5345:         }
                   5346:     } else {
                   5347:         foreach my $block (keys(%commblocks)) {
                   5348:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5349:                 my ($start,$end) = ($1,$2);
                   5350:                 if ($start <= time && $end >= time) {
                   5351:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5352:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5353:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5354:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5355:                                     push(@blockers,$block);
                   5356:                                 }
                   5357:                             }
                   5358:                         }
                   5359:                     }
                   5360:                 }
                   5361:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5362:                 my $item = $1;
                   5363:                 my $timersymb = $item; 
                   5364:                 my $type = 'map';
                   5365:                 if ($item eq 'course') {
                   5366:                     $type = 'course';
                   5367:                 } elsif ($item =~ /___\d+___/) {
                   5368:                     $type = 'resource';
                   5369:                 } else {
                   5370:                     $timersymb = &Apache::lonnet::symbread($item);
                   5371:                 }
                   5372:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5373:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5374:                 if ($start && $end) {
                   5375:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5376:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5377:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5378:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5379:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5380:                                         push(@blockers,$block);
                   5381:                                         $triggered{$block} = {
                   5382:                                                                start => $start,
                   5383:                                                                end   => $end,
                   5384:                                                                type  => $type,
                   5385:                                                              };
                   5386:                                     }
                   5387:                                 }
                   5388:                             }
1.1062    raeburn  5389:                         }
                   5390:                     }
1.490     raeburn  5391:                 }
1.1062    raeburn  5392:             }
                   5393:         }
                   5394:     }
                   5395:     foreach my $blocker (@blockers) {
                   5396:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5397:             &parse_block_record($commblocks{$blocker});
                   5398:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5399:         my ($start,$end,$triggertype);
                   5400:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5401:             ($start,$end) = ($1,$2);
                   5402:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5403:             $start = $triggered{$blocker}{'start'};
                   5404:             $end = $triggered{$blocker}{'end'};
                   5405:             $triggertype = $triggered{$blocker}{'type'};
                   5406:         }
                   5407:         if ($start) {
                   5408:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5409:             if ($triggertype) {
                   5410:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5411:             } else {
                   5412:                 push(@{$$setters{$course}{'triggers'}},0);
                   5413:             }
                   5414:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5415:                 $startblock = $start;
                   5416:                 if ($triggertype) {
                   5417:                     $triggerblock = $blocker;
1.474     raeburn  5418:                 }
                   5419:             }
1.1062    raeburn  5420:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5421:                $endblock = $end;
                   5422:                if ($triggertype) {
                   5423:                    $triggerblock = $blocker;
                   5424:                }
                   5425:             }
1.474     raeburn  5426:         }
                   5427:     }
1.1062    raeburn  5428:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5429: }
                   5430: 
                   5431: sub parse_block_record {
                   5432:     my ($record) = @_;
                   5433:     my ($setuname,$setudom,$title,$blocks);
                   5434:     if (ref($record) eq 'HASH') {
                   5435:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5436:         $title = &unescape($record->{'event'});
                   5437:         $blocks = $record->{'blocks'};
                   5438:     } else {
                   5439:         my @data = split(/:/,$record,3);
                   5440:         if (scalar(@data) eq 2) {
                   5441:             $title = $data[1];
                   5442:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5443:         } else {
                   5444:             ($setuname,$setudom,$title) = @data;
                   5445:         }
                   5446:         $blocks = { 'com' => 'on' };
                   5447:     }
                   5448:     return ($setuname,$setudom,$title,$blocks);
                   5449: }
                   5450: 
1.854     kalberla 5451: sub blocking_status {
1.1347  ! raeburn  5452:     my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5453:     my %setters;
1.890     droeschl 5454: 
1.1061    raeburn  5455: # check for active blocking
1.1062    raeburn  5456:     my ($startblock,$endblock,$triggerblock) = 
1.1347  ! raeburn  5457:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5458:     my $blocked = 0;
                   5459:     if ($startblock && $endblock) {
                   5460:         $blocked = 1;
                   5461:     }
1.890     droeschl 5462: 
1.1061    raeburn  5463: # caller just wants to know whether a block is active
                   5464:     if (!wantarray) { return $blocked; }
                   5465: 
                   5466: # build a link to a popup window containing the details
                   5467:     my $querystring  = "?activity=$activity";
                   5468: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5469:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5470:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5471:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5472:     } elsif ($activity eq 'docs') {
1.1347  ! raeburn  5473:         my $showurl = &Apache::lonenc::check_encrypt($url);
        !          5474:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
        !          5475:         if ($symb) {
        !          5476:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
        !          5477:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
        !          5478:         }
1.1062    raeburn  5479:     }
1.1061    raeburn  5480: 
                   5481:     my $output .= <<'END_MYBLOCK';
                   5482: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5483:     var options = "width=" + w + ",height=" + h + ",";
                   5484:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5485:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5486:     var newWin = window.open(url, wdwName, options);
                   5487:     newWin.focus();
                   5488: }
1.890     droeschl 5489: END_MYBLOCK
1.854     kalberla 5490: 
1.1061    raeburn  5491:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5492:   
1.1061    raeburn  5493:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5494:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5495:     my $class = 'LC_comblock';
1.1062    raeburn  5496:     if ($activity eq 'docs') {
                   5497:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5498:         $class = '';
1.1063    raeburn  5499:     } elsif ($activity eq 'printout') {
                   5500:         $text = &mt('Printing Blocked');
1.1232    raeburn  5501:     } elsif ($activity eq 'passwd') {
                   5502:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5503:     } elsif ($activity eq 'grades') {
                   5504:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5505:     } elsif ($activity eq 'search') {
                   5506:         $text = &mt('Search Blocked');
1.1282    raeburn  5507:     } elsif ($activity eq 'alert') {
                   5508:         $text = &mt('Checking Critical Messages Blocked');
                   5509:     } elsif ($activity eq 'reinit') {
                   5510:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5511:     }
1.1061    raeburn  5512:     $output .= <<"END_BLOCK";
1.1217    raeburn  5513: <div class='$class'>
1.869     kalberla 5514:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5515:   title='$text'>
                   5516:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5517:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5518:   title='$text'>$text</a>
1.867     kalberla 5519: </div>
                   5520: 
                   5521: END_BLOCK
1.474     raeburn  5522: 
1.1061    raeburn  5523:     return ($blocked, $output);
1.854     kalberla 5524: }
1.490     raeburn  5525: 
1.60      matthew  5526: ###############################################
                   5527: 
1.682     raeburn  5528: sub check_ip_acc {
1.1201    raeburn  5529:     my ($acc,$clientip)=@_;
1.682     raeburn  5530:     &Apache::lonxml::debug("acc is $acc");
                   5531:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5532:         return 1;
                   5533:     }
1.1339    raeburn  5534:     my ($ip,$allowed);
                   5535:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5536:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5537:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5538:     } else {
                   5539:         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
                   5540:     }
1.682     raeburn  5541: 
                   5542:     my $name;
1.1219    raeburn  5543:     my %access = (
                   5544:                      allowfrom => 1,
                   5545:                      denyfrom  => 0,
                   5546:                  );
                   5547:     my @allows;
                   5548:     my @denies;
                   5549:     foreach my $item (split(',',$acc)) {
                   5550:         $item =~ s/^\s*//;
                   5551:         $item =~ s/\s*$//;
                   5552:         my $pattern;
                   5553:         if ($item =~ /^\!(.+)$/) {
                   5554:             push(@denies,$1);
                   5555:         } else {
                   5556:             push(@allows,$item);
                   5557:         }
                   5558:    }
                   5559:    my $numdenies = scalar(@denies);
                   5560:    my $numallows = scalar(@allows);
                   5561:    my $count = 0;
                   5562:    foreach my $pattern (@denies,@allows) {
                   5563:         $count ++; 
                   5564:         my $acctype = 'allowfrom';
                   5565:         if ($count <= $numdenies) {
                   5566:             $acctype = 'denyfrom';
                   5567:         }
1.682     raeburn  5568:         if ($pattern =~ /\*$/) {
                   5569:             #35.8.*
                   5570:             $pattern=~s/\*//;
1.1219    raeburn  5571:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5572:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5573:             #35.8.3.[34-56]
                   5574:             my $low=$2;
                   5575:             my $high=$3;
                   5576:             $pattern=$1;
                   5577:             if ($ip =~ /^\Q$pattern\E/) {
                   5578:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5579:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5580:             }
                   5581:         } elsif ($pattern =~ /^\*/) {
                   5582:             #*.msu.edu
                   5583:             $pattern=~s/\*//;
                   5584:             if (!defined($name)) {
                   5585:                 use Socket;
                   5586:                 my $netaddr=inet_aton($ip);
                   5587:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5588:             }
1.1219    raeburn  5589:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5590:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5591:             #127.0.0.1
1.1219    raeburn  5592:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5593:         } else {
                   5594:             #some.name.com
                   5595:             if (!defined($name)) {
                   5596:                 use Socket;
                   5597:                 my $netaddr=inet_aton($ip);
                   5598:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5599:             }
1.1219    raeburn  5600:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5601:         }
                   5602:         if ($allowed =~ /^(0|1)$/) { last; }
                   5603:     }
                   5604:     if ($allowed eq '') {
                   5605:         if ($numdenies && !$numallows) {
                   5606:             $allowed = 1;
                   5607:         } else {
                   5608:             $allowed = 0;
1.682     raeburn  5609:         }
                   5610:     }
                   5611:     return $allowed;
                   5612: }
                   5613: 
                   5614: ###############################################
                   5615: 
1.60      matthew  5616: =pod
                   5617: 
1.112     bowersj2 5618: =head1 Domain Template Functions
                   5619: 
                   5620: =over 4
                   5621: 
                   5622: =item * &determinedomain()
1.60      matthew  5623: 
                   5624: Inputs: $domain (usually will be undef)
                   5625: 
1.63      www      5626: Returns: Determines which domain should be used for designs
1.60      matthew  5627: 
                   5628: =cut
1.54      www      5629: 
1.60      matthew  5630: ###############################################
1.63      www      5631: sub determinedomain {
                   5632:     my $domain=shift;
1.531     albertel 5633:     if (! $domain) {
1.60      matthew  5634:         # Determine domain if we have not been given one
1.893     raeburn  5635:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5636:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5637:         if ($env{'request.role.domain'}) { 
                   5638:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5639:         }
                   5640:     }
1.63      www      5641:     return $domain;
                   5642: }
                   5643: ###############################################
1.517     raeburn  5644: 
1.518     albertel 5645: sub devalidate_domconfig_cache {
                   5646:     my ($udom)=@_;
                   5647:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5648: }
                   5649: 
                   5650: # ---------------------- Get domain configuration for a domain
                   5651: sub get_domainconf {
                   5652:     my ($udom) = @_;
                   5653:     my $cachetime=1800;
                   5654:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5655:     if (defined($cached)) { return %{$result}; }
                   5656: 
                   5657:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5658: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5659:     my (%designhash,%legacy);
1.518     albertel 5660:     if (keys(%domconfig) > 0) {
                   5661:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5662:             if (keys(%{$domconfig{'login'}})) {
                   5663:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5664:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5665:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5666:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5667:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5668:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5669:                                         if ($key eq 'loginvia') {
                   5670:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5671:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5672:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5673:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5674: 
                   5675:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5676:                                                 } else {
                   5677:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5678:                                                 }
1.948     raeburn  5679:                                             }
1.1208    raeburn  5680:                                         } elsif ($key eq 'headtag') {
                   5681:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5682:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5683:                                             }
1.946     raeburn  5684:                                         }
1.1208    raeburn  5685:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5686:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5687:                                         }
1.946     raeburn  5688:                                     }
                   5689:                                 }
                   5690:                             }
                   5691:                         } else {
                   5692:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5693:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5694:                                     $domconfig{'login'}{$key}{$img};
                   5695:                             }
1.699     raeburn  5696:                         }
                   5697:                     } else {
                   5698:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5699:                     }
1.632     raeburn  5700:                 }
                   5701:             } else {
                   5702:                 $legacy{'login'} = 1;
1.518     albertel 5703:             }
1.632     raeburn  5704:         } else {
                   5705:             $legacy{'login'} = 1;
1.518     albertel 5706:         }
                   5707:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5708:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5709:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5710:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5711:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5712:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5713:                         }
1.518     albertel 5714:                     }
                   5715:                 }
1.632     raeburn  5716:             } else {
                   5717:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5718:             }
1.632     raeburn  5719:         } else {
                   5720:             $legacy{'rolecolors'} = 1;
1.518     albertel 5721:         }
1.948     raeburn  5722:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5723:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5724:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5725:             }
                   5726:         }
1.632     raeburn  5727:         if (keys(%legacy) > 0) {
                   5728:             my %legacyhash = &get_legacy_domconf($udom);
                   5729:             foreach my $item (keys(%legacyhash)) {
                   5730:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5731:                     if ($legacy{'login'}) { 
                   5732:                         $designhash{$item} = $legacyhash{$item};
                   5733:                     }
                   5734:                 } else {
                   5735:                     if ($legacy{'rolecolors'}) {
                   5736:                         $designhash{$item} = $legacyhash{$item};
                   5737:                     }
1.518     albertel 5738:                 }
                   5739:             }
                   5740:         }
1.632     raeburn  5741:     } else {
                   5742:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5743:     }
                   5744:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5745: 				  $cachetime);
                   5746:     return %designhash;
                   5747: }
                   5748: 
1.632     raeburn  5749: sub get_legacy_domconf {
                   5750:     my ($udom) = @_;
                   5751:     my %legacyhash;
                   5752:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5753:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5754:     if (-e $designfile) {
1.1317    raeburn  5755:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5756:             while (my $line = <$fh>) {
                   5757:                 next if ($line =~ /^\#/);
                   5758:                 chomp($line);
                   5759:                 my ($key,$val)=(split(/\=/,$line));
                   5760:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5761:             }
                   5762:             close($fh);
                   5763:         }
                   5764:     }
1.1026    raeburn  5765:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5766:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5767:     }
                   5768:     return %legacyhash;
                   5769: }
                   5770: 
1.63      www      5771: =pod
                   5772: 
1.112     bowersj2 5773: =item * &domainlogo()
1.63      www      5774: 
                   5775: Inputs: $domain (usually will be undef)
                   5776: 
                   5777: Returns: A link to a domain logo, if the domain logo exists.
                   5778: If the domain logo does not exist, a description of the domain.
                   5779: 
                   5780: =cut
1.112     bowersj2 5781: 
1.63      www      5782: ###############################################
                   5783: sub domainlogo {
1.517     raeburn  5784:     my $domain = &determinedomain(shift);
1.518     albertel 5785:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5786:     # See if there is a logo
                   5787:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5788:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5789:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5790: 	    if ($imgsrc =~ m{^/res/}) {
                   5791: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5792: 		&Apache::lonnet::repcopy($local_name);
                   5793: 	    }
                   5794: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5795:         } 
                   5796:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5797:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5798:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5799:     } else {
1.60      matthew  5800:         return '';
1.59      www      5801:     }
                   5802: }
1.63      www      5803: ##############################################
                   5804: 
                   5805: =pod
                   5806: 
1.112     bowersj2 5807: =item * &designparm()
1.63      www      5808: 
                   5809: Inputs: $which parameter; $domain (usually will be undef)
                   5810: 
                   5811: Returns: value of designparamter $which
                   5812: 
                   5813: =cut
1.112     bowersj2 5814: 
1.397     albertel 5815: 
1.400     albertel 5816: ##############################################
1.397     albertel 5817: sub designparm {
                   5818:     my ($which,$domain)=@_;
                   5819:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5820:         return $env{'environment.color.'.$which};
1.96      www      5821:     }
1.63      www      5822:     $domain=&determinedomain($domain);
1.1016    raeburn  5823:     my %domdesign;
                   5824:     unless ($domain eq 'public') {
                   5825:         %domdesign = &get_domainconf($domain);
                   5826:     }
1.520     raeburn  5827:     my $output;
1.517     raeburn  5828:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5829:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5830:     } else {
1.520     raeburn  5831:         $output = $defaultdesign{$which};
                   5832:     }
                   5833:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5834:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5835:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5836:             if ($output =~ m{^/res/}) {
                   5837:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5838:                 &Apache::lonnet::repcopy($local_name);
                   5839:             }
1.520     raeburn  5840:             $output = &lonhttpdurl($output);
                   5841:         }
1.63      www      5842:     }
1.520     raeburn  5843:     return $output;
1.63      www      5844: }
1.59      www      5845: 
1.822     bisitz   5846: ##############################################
                   5847: =pod
                   5848: 
1.832     bisitz   5849: =item * &authorspace()
                   5850: 
1.1028    raeburn  5851: Inputs: $url (usually will be undef).
1.832     bisitz   5852: 
1.1132    raeburn  5853: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5854:          directory being viewed (or for which action is being taken). 
                   5855:          If $url is provided, and begins /priv/<domain>/<uname>
                   5856:          the path will be that portion of the $context argument.
                   5857:          Otherwise the path will be for the author space of the current
                   5858:          user when the current role is author, or for that of the 
                   5859:          co-author/assistant co-author space when the current role 
                   5860:          is co-author or assistant co-author.
1.832     bisitz   5861: 
                   5862: =cut
                   5863: 
                   5864: sub authorspace {
1.1028    raeburn  5865:     my ($url) = @_;
                   5866:     if ($url ne '') {
                   5867:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5868:            return $1;
                   5869:         }
                   5870:     }
1.832     bisitz   5871:     my $caname = '';
1.1024    www      5872:     my $cadom = '';
1.1028    raeburn  5873:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5874:         ($cadom,$caname) =
1.832     bisitz   5875:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5876:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5877:         $caname = $env{'user.name'};
1.1024    www      5878:         $cadom = $env{'user.domain'};
1.832     bisitz   5879:     }
1.1028    raeburn  5880:     if (($caname ne '') && ($cadom ne '')) {
                   5881:         return "/priv/$cadom/$caname/";
                   5882:     }
                   5883:     return;
1.832     bisitz   5884: }
                   5885: 
                   5886: ##############################################
                   5887: =pod
                   5888: 
1.822     bisitz   5889: =item * &head_subbox()
                   5890: 
                   5891: Inputs: $content (contains HTML code with page functions, etc.)
                   5892: 
                   5893: Returns: HTML div with $content
                   5894:          To be included in page header
                   5895: 
                   5896: =cut
                   5897: 
                   5898: sub head_subbox {
                   5899:     my ($content)=@_;
                   5900:     my $output =
1.993     raeburn  5901:         '<div class="LC_head_subbox">'
1.822     bisitz   5902:        .$content
                   5903:        .'</div>'
                   5904: }
                   5905: 
                   5906: ##############################################
                   5907: =pod
                   5908: 
                   5909: =item * &CSTR_pageheader()
                   5910: 
1.1026    raeburn  5911: Input: (optional) filename from which breadcrumb trail is built.
                   5912:        In most cases no input as needed, as $env{'request.filename'}
                   5913:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5914: 
                   5915: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5916:          To be included on Authoring Space pages
1.822     bisitz   5917: 
                   5918: =cut
                   5919: 
                   5920: sub CSTR_pageheader {
1.1026    raeburn  5921:     my ($trailfile) = @_;
                   5922:     if ($trailfile eq '') {
                   5923:         $trailfile = $env{'request.filename'};
                   5924:     }
                   5925: 
                   5926: # this is for resources; directories have customtitle, and crumbs
                   5927: # and select recent are created in lonpubdir.pm
                   5928: 
                   5929:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5930:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5931:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5932:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5933:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5934: 
                   5935:     my $parentpath = '';
                   5936:     my $lastitem = '';
                   5937:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5938:         $parentpath = $1;
                   5939:         $lastitem = $2;
                   5940:     } else {
                   5941:         $lastitem = $thisdisfn;
                   5942:     }
1.921     bisitz   5943: 
1.1246    raeburn  5944:     my ($crsauthor,$title);
                   5945:     if (($env{'request.course.id'}) &&
                   5946:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5947:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5948:         $crsauthor = 1;
                   5949:         $title = &mt('Course Authoring Space');
                   5950:     } else {
                   5951:         $title = &mt('Authoring Space');
                   5952:     }
                   5953: 
1.1314    raeburn  5954:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  5955:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  5956:         $target = '';
                   5957:         $crumbtarget = '';
1.1313    raeburn  5958:     }
                   5959: 
1.921     bisitz   5960:     my $output =
1.822     bisitz   5961:          '<div>'
                   5962:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5963:         .'<b>'.$title.'</b> '
1.1314    raeburn  5964:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5965:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5966: 
                   5967:     if ($lastitem) {
                   5968:         $output .=
                   5969:              '<span class="LC_filename">'
                   5970:             .$lastitem
                   5971:             .'</span>';
                   5972:     }
1.1245    raeburn  5973: 
1.1246    raeburn  5974:     if ($crsauthor) {
                   5975:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5976:     } else {
                   5977:         $output .=
                   5978:              '<br />'
1.1314    raeburn  5979:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  5980:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5981:             .'</form>'
                   5982:             .&Apache::lonmenu::constspaceform();
                   5983:     }
                   5984:     $output .= '</div>';
1.921     bisitz   5985: 
                   5986:     return $output;
1.822     bisitz   5987: }
                   5988: 
1.60      matthew  5989: ###############################################
                   5990: ###############################################
                   5991: 
                   5992: =pod
                   5993: 
1.112     bowersj2 5994: =back
                   5995: 
1.549     albertel 5996: =head1 HTML Helpers
1.112     bowersj2 5997: 
                   5998: =over 4
                   5999: 
                   6000: =item * &bodytag()
1.60      matthew  6001: 
                   6002: Returns a uniform header for LON-CAPA web pages.
                   6003: 
                   6004: Inputs: 
                   6005: 
1.112     bowersj2 6006: =over 4
                   6007: 
                   6008: =item * $title, A title to be displayed on the page.
                   6009: 
                   6010: =item * $function, the current role (can be undef).
                   6011: 
                   6012: =item * $addentries, extra parameters for the <body> tag.
                   6013: 
                   6014: =item * $bodyonly, if defined, only return the <body> tag.
                   6015: 
                   6016: =item * $domain, if defined, force a given domain.
                   6017: 
                   6018: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6019:             text interface only)
1.60      matthew  6020: 
1.814     bisitz   6021: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6022:                      navigational links
1.317     albertel 6023: 
1.338     albertel 6024: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6025: 
1.460     albertel 6026: =item * $args, optional argument valid values are
                   6027:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6028:             use_absolute     -> for external resource or syllabus, this will
                   6029:                                 contain https://<hostname> if server uses
                   6030:                                 https (as per hosts.tab), but request is for http
                   6031:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6032: 
1.1096    raeburn  6033: =item * $advtoolsref, optional argument, ref to an array containing
                   6034:             inlineremote items to be added in "Functions" menu below
                   6035:             breadcrumbs.
                   6036: 
1.1316    raeburn  6037: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6038:             course, if LON-CAPA is in LTI Provider context. Value is
                   6039:             the scope of use, i.e., launch was for access to a single, a map
                   6040:             or the entire course.
                   6041: 
                   6042: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6043:             context, this will contain the URL for the landing item in
                   6044:             the course, after launch from an LTI Consumer
                   6045: 
1.1318    raeburn  6046: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6047:             context, this will contain a reference to hash of items
                   6048:             to be included in the page header and/or inline menu.
                   6049: 
1.112     bowersj2 6050: =back
                   6051: 
1.60      matthew  6052: Returns: A uniform header for LON-CAPA web pages.  
                   6053: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6054: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6055: other decorations will be returned.
                   6056: 
                   6057: =cut
                   6058: 
1.54      www      6059: sub bodytag {
1.831     bisitz   6060:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1318    raeburn  6061:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,$ltimenu)=@_;
1.339     albertel 6062: 
1.954     raeburn  6063:     my $public;
                   6064:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6065:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6066:         $public = 1;
                   6067:     }
1.460     albertel 6068:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6069:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6070:     my $hostname = $args->{'hostname'};
1.339     albertel 6071: 
1.183     matthew  6072:     $function = &get_users_function() if (!$function);
1.339     albertel 6073:     my $img =    &designparm($function.'.img',$domain);
                   6074:     my $font =   &designparm($function.'.font',$domain);
                   6075:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6076: 
1.803     bisitz   6077:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6078: 		   'bgcolor' => $pgbg,
1.339     albertel 6079: 		   'text'    => $font,
                   6080:                    'alink'   => &designparm($function.'.alink',$domain),
                   6081: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6082: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6083:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6084: 
1.63      www      6085:  # role and realm
1.1178    raeburn  6086:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6087:     if ($realm) {
                   6088:         $realm = '/'.$realm;
                   6089:     }
1.378     raeburn  6090:     if ($role  eq 'ca') {
1.479     albertel 6091:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6092:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6093:     } 
1.55      www      6094: # realm
1.258     albertel 6095:     if ($env{'request.course.id'}) {
1.378     raeburn  6096:         if ($env{'request.role'} !~ /^cr/) {
                   6097:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6098:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6099:             if ($env{'request.role.desc'}) {
                   6100:                 $role = $env{'request.role.desc'};
                   6101:             } else {
                   6102:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6103:             }
1.1257    raeburn  6104:         } else {
                   6105:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6106:         }
1.898     raeburn  6107:         if ($env{'request.course.sec'}) {
                   6108:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   6109:         }   
1.359     albertel 6110: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  6111:     } else {
                   6112:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6113:     }
1.433     albertel 6114: 
1.359     albertel 6115:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6116: 
1.438     albertel 6117:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6118: 
1.101     www      6119: # construct main body tag
1.359     albertel 6120:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6121: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6122: 
1.1131    raeburn  6123:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6124: 
1.1130    raeburn  6125:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6126:         return $bodytag;
1.1130    raeburn  6127:     }
1.359     albertel 6128: 
1.954     raeburn  6129:     if ($public) {
1.433     albertel 6130: 	undef($role);
                   6131:     }
1.1318    raeburn  6132: 
                   6133:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   6134:         if (ref($ltimenu) eq 'HASH') {
                   6135:             unless ($ltimenu->{'role'}) {
                   6136:                 undef($role);
                   6137:             }
                   6138:             unless ($ltimenu->{'coursetitle'}) {
                   6139:                 $realm='&nbsp;';
                   6140:             }
                   6141:         }
                   6142:     }
                   6143: 
1.762     bisitz   6144:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6145:     #
                   6146:     # Extra info if you are the DC
                   6147:     my $dc_info = '';
                   6148:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   6149:                         $env{'course.'.$env{'request.course.id'}.
                   6150:                                  '.domain'}.'/'})) {
                   6151:         my $cid = $env{'request.course.id'};
1.917     raeburn  6152:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6153:         $dc_info =~ s/\s+$//;
1.359     albertel 6154:     }
                   6155: 
1.1237    raeburn  6156:     my $crstype;
                   6157:     if ($env{'request.course.id'}) {
                   6158:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   6159:     } elsif ($args->{'crstype'}) {
                   6160:         $crstype = $args->{'crstype'};
                   6161:     }
                   6162:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6163:         undef($role);
                   6164:     } else {
1.1242    raeburn  6165:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6166:     }
1.853     droeschl 6167: 
1.903     droeschl 6168:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6169: 
                   6170:         #    if ($env{'request.state'} eq 'construct') {
                   6171:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6172:         #    }
                   6173: 
1.1130    raeburn  6174:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6175:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6176: 
1.1318    raeburn  6177:         unless ($args->{'no_primary_menu'}) {
                   6178:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu);
1.359     albertel 6179: 
1.1318    raeburn  6180:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6181:                 if ($dc_info) {
                   6182:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6183:                 }
                   6184:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6185:                                <em>$realm</em> $dc_info</div>|;
                   6186:                 return $bodytag;
                   6187:             }
1.894     droeschl 6188: 
1.1318    raeburn  6189:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6190:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6191:             }
1.916     droeschl 6192: 
1.1318    raeburn  6193:             $bodytag .= $right;
1.852     droeschl 6194: 
1.1318    raeburn  6195:             if ($dc_info) {
                   6196:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6197:             }
                   6198:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6199:         }
1.916     droeschl 6200: 
1.1169    raeburn  6201:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6202:         if ($args->{'no_secondary_menu'}) {
                   6203:             return $bodytag;
                   6204:         }
1.1169    raeburn  6205:         #don't show menus for public users
1.954     raeburn  6206:         if (!$public){
1.1318    raeburn  6207:             unless ($args->{'no_inline_menu'}) {
                   6208:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6209:                                                             $args->{'no_primary_menu'});
                   6210:             }
1.903     droeschl 6211:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6212:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6213:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6214:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6215:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6216:             } elsif ($forcereg) {
                   6217:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6218:                                                             $args->{'group'},
1.1274    raeburn  6219:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6220:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6221:             } else {
                   6222:                 $bodytag .= 
                   6223:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6224:                                                         $forcereg,$args->{'group'},
                   6225:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6226:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6227:             }
1.903     droeschl 6228:         }else{
                   6229:             # this is to seperate menu from content when there's no secondary
                   6230:             # menu. Especially needed for public accessible ressources.
                   6231:             $bodytag .= '<hr style="clear:both" />';
                   6232:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6233:         }
1.903     droeschl 6234: 
1.235     raeburn  6235:         return $bodytag;
1.182     matthew  6236: }
                   6237: 
1.917     raeburn  6238: sub dc_courseid_toggle {
                   6239:     my ($dc_info) = @_;
1.980     raeburn  6240:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6241:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6242:            &mt('(More ...)').'</a></span>'.
                   6243:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6244: }
                   6245: 
1.330     albertel 6246: sub make_attr_string {
                   6247:     my ($register,$attr_ref) = @_;
                   6248: 
                   6249:     if ($attr_ref && !ref($attr_ref)) {
                   6250: 	die("addentries Must be a hash ref ".
                   6251: 	    join(':',caller(1))." ".
                   6252: 	    join(':',caller(0))." ");
                   6253:     }
                   6254: 
                   6255:     if ($register) {
1.339     albertel 6256: 	my ($on_load,$on_unload);
                   6257: 	foreach my $key (keys(%{$attr_ref})) {
                   6258: 	    if      (lc($key) eq 'onload') {
                   6259: 		$on_load.=$attr_ref->{$key}.';';
                   6260: 		delete($attr_ref->{$key});
                   6261: 
                   6262: 	    } elsif (lc($key) eq 'onunload') {
                   6263: 		$on_unload.=$attr_ref->{$key}.';';
                   6264: 		delete($attr_ref->{$key});
                   6265: 	    }
                   6266: 	}
1.953     droeschl 6267: 	$attr_ref->{'onload'}  = $on_load;
                   6268: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6269:     }
1.339     albertel 6270: 
1.330     albertel 6271:     my $attr_string;
1.1159    raeburn  6272:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6273: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6274:     }
                   6275:     return $attr_string;
                   6276: }
                   6277: 
                   6278: 
1.182     matthew  6279: ###############################################
1.251     albertel 6280: ###############################################
                   6281: 
                   6282: =pod
                   6283: 
                   6284: =item * &endbodytag()
                   6285: 
                   6286: Returns a uniform footer for LON-CAPA web pages.
                   6287: 
1.635     raeburn  6288: Inputs: 1 - optional reference to an args hash
                   6289: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6290: a 'Continue' link is not displayed if the page contains an
                   6291: internal redirect in the <head></head> section,
                   6292: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6293: 
                   6294: =cut
                   6295: 
                   6296: sub endbodytag {
1.635     raeburn  6297:     my ($args) = @_;
1.1080    raeburn  6298:     my $endbodytag;
                   6299:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6300:         $endbodytag='</body>';
                   6301:     }
1.315     albertel 6302:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6303:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6304: 	    $endbodytag=
                   6305: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6306: 	        &mt('Continue').'</a>'.
                   6307: 	        $endbodytag;
                   6308:         }
1.315     albertel 6309:     }
1.251     albertel 6310:     return $endbodytag;
                   6311: }
                   6312: 
1.352     albertel 6313: =pod
                   6314: 
                   6315: =item * &standard_css()
                   6316: 
                   6317: Returns a style sheet
                   6318: 
                   6319: Inputs: (all optional)
                   6320:             domain         -> force to color decorate a page for a specific
                   6321:                                domain
                   6322:             function       -> force usage of a specific rolish color scheme
                   6323:             bgcolor        -> override the default page bgcolor
                   6324: 
                   6325: =cut
                   6326: 
1.343     albertel 6327: sub standard_css {
1.345     albertel 6328:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6329:     $function  = &get_users_function() if (!$function);
                   6330:     my $img    = &designparm($function.'.img',   $domain);
                   6331:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6332:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6333:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6334: #second colour for later usage
1.345     albertel 6335:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6336:     my $pgbg_or_bgcolor =
                   6337: 	         $bgcolor ||
1.352     albertel 6338: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6339:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6340:     my $alink  = &designparm($function.'.alink', $domain);
                   6341:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6342:     my $link   = &designparm($function.'.link',  $domain);
                   6343: 
1.602     albertel 6344:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6345:     my $mono                 = 'monospace';
1.850     bisitz   6346:     my $data_table_head      = $sidebg;
                   6347:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6348:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6349:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6350:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6351:     my $mail_new             = '#FFBB77';
                   6352:     my $mail_new_hover       = '#DD9955';
                   6353:     my $mail_read            = '#BBBB77';
                   6354:     my $mail_read_hover      = '#999944';
                   6355:     my $mail_replied         = '#AAAA88';
                   6356:     my $mail_replied_hover   = '#888855';
                   6357:     my $mail_other           = '#99BBBB';
                   6358:     my $mail_other_hover     = '#669999';
1.391     albertel 6359:     my $table_header         = '#DDDDDD';
1.489     raeburn  6360:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6361:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6362:     my $button_hover         = '#BF2317';
1.392     albertel 6363: 
1.608     albertel 6364:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6365:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6366:                                              : '0 3px 0 4px';
1.448     albertel 6367: 
1.523     albertel 6368: 
1.343     albertel 6369:     return <<END;
1.947     droeschl 6370: 
                   6371: /* needed for iframe to allow 100% height in FF */
                   6372: body, html { 
                   6373:     margin: 0;
                   6374:     padding: 0 0.5%;
                   6375:     height: 99%; /* to avoid scrollbars */
                   6376: }
                   6377: 
1.795     www      6378: body {
1.911     bisitz   6379:   font-family: $sans;
                   6380:   line-height:130%;
                   6381:   font-size:0.83em;
                   6382:   color:$font;
1.795     www      6383: }
                   6384: 
1.959     onken    6385: a:focus,
                   6386: a:focus img {
1.795     www      6387:   color: red;
                   6388: }
1.698     harmsja  6389: 
1.911     bisitz   6390: form, .inline {
                   6391:   display: inline;
1.795     www      6392: }
1.721     harmsja  6393: 
1.795     www      6394: .LC_right {
1.911     bisitz   6395:   text-align:right;
1.795     www      6396: }
                   6397: 
                   6398: .LC_middle {
1.911     bisitz   6399:   vertical-align:middle;
1.795     www      6400: }
1.721     harmsja  6401: 
1.1130    raeburn  6402: .LC_floatleft {
                   6403:   float: left;
                   6404: }
                   6405: 
                   6406: .LC_floatright {
                   6407:   float: right;
                   6408: }
                   6409: 
1.911     bisitz   6410: .LC_400Box {
                   6411:   width:400px;
                   6412: }
1.721     harmsja  6413: 
1.947     droeschl 6414: .LC_iframecontainer {
                   6415:     width: 98%;
                   6416:     margin: 0;
                   6417:     position: fixed;
                   6418:     top: 8.5em;
                   6419:     bottom: 0;
                   6420: }
                   6421: 
                   6422: .LC_iframecontainer iframe{
                   6423:     border: none;
                   6424:     width: 100%;
                   6425:     height: 100%;
                   6426: }
                   6427: 
1.778     bisitz   6428: .LC_filename {
                   6429:   font-family: $mono;
                   6430:   white-space:pre;
1.921     bisitz   6431:   font-size: 120%;
1.778     bisitz   6432: }
                   6433: 
                   6434: .LC_fileicon {
                   6435:   border: none;
                   6436:   height: 1.3em;
                   6437:   vertical-align: text-bottom;
                   6438:   margin-right: 0.3em;
                   6439:   text-decoration:none;
                   6440: }
                   6441: 
1.1008    www      6442: .LC_setting {
                   6443:   text-decoration:underline;
                   6444: }
                   6445: 
1.350     albertel 6446: .LC_error {
                   6447:   color: red;
                   6448: }
1.795     www      6449: 
1.1097    bisitz   6450: .LC_warning {
                   6451:   color: darkorange;
                   6452: }
                   6453: 
1.457     albertel 6454: .LC_diff_removed {
1.733     bisitz   6455:   color: red;
1.394     albertel 6456: }
1.532     albertel 6457: 
                   6458: .LC_info,
1.457     albertel 6459: .LC_success,
                   6460: .LC_diff_added {
1.350     albertel 6461:   color: green;
                   6462: }
1.795     www      6463: 
1.802     bisitz   6464: div.LC_confirm_box {
                   6465:   background-color: #FAFAFA;
                   6466:   border: 1px solid $lg_border_color;
                   6467:   margin-right: 0;
                   6468:   padding: 5px;
                   6469: }
                   6470: 
                   6471: div.LC_confirm_box .LC_error img,
                   6472: div.LC_confirm_box .LC_success img {
                   6473:   vertical-align: middle;
                   6474: }
                   6475: 
1.1242    raeburn  6476: .LC_maxwidth {
                   6477:   max-width: 100%;
                   6478:   height: auto;
                   6479: }
                   6480: 
1.1243    raeburn  6481: .LC_textsize_mobile {
                   6482:   \@media only screen and (max-device-width: 480px) {
                   6483:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6484:   }
                   6485: }
                   6486: 
1.440     albertel 6487: .LC_icon {
1.771     droeschl 6488:   border: none;
1.790     droeschl 6489:   vertical-align: middle;
1.771     droeschl 6490: }
                   6491: 
1.543     albertel 6492: .LC_docs_spacer {
                   6493:   width: 25px;
                   6494:   height: 1px;
1.771     droeschl 6495:   border: none;
1.543     albertel 6496: }
1.346     albertel 6497: 
1.532     albertel 6498: .LC_internal_info {
1.735     bisitz   6499:   color: #999999;
1.532     albertel 6500: }
                   6501: 
1.794     www      6502: .LC_discussion {
1.1050    www      6503:   background: $data_table_dark;
1.911     bisitz   6504:   border: 1px solid black;
                   6505:   margin: 2px;
1.794     www      6506: }
                   6507: 
                   6508: .LC_disc_action_left {
1.1050    www      6509:   background: $sidebg;
1.911     bisitz   6510:   text-align: left;
1.1050    www      6511:   padding: 4px;
                   6512:   margin: 2px;
1.794     www      6513: }
                   6514: 
                   6515: .LC_disc_action_right {
1.1050    www      6516:   background: $sidebg;
1.911     bisitz   6517:   text-align: right;
1.1050    www      6518:   padding: 4px;
                   6519:   margin: 2px;
1.794     www      6520: }
                   6521: 
                   6522: .LC_disc_new_item {
1.911     bisitz   6523:   background: white;
                   6524:   border: 2px solid red;
1.1050    www      6525:   margin: 4px;
                   6526:   padding: 4px;
1.794     www      6527: }
                   6528: 
                   6529: .LC_disc_old_item {
1.911     bisitz   6530:   background: white;
1.1050    www      6531:   margin: 4px;
                   6532:   padding: 4px;
1.794     www      6533: }
                   6534: 
1.458     albertel 6535: table.LC_pastsubmission {
                   6536:   border: 1px solid black;
                   6537:   margin: 2px;
                   6538: }
                   6539: 
1.924     bisitz   6540: table#LC_menubuttons {
1.345     albertel 6541:   width: 100%;
                   6542:   background: $pgbg;
1.392     albertel 6543:   border: 2px;
1.402     albertel 6544:   border-collapse: separate;
1.803     bisitz   6545:   padding: 0;
1.345     albertel 6546: }
1.392     albertel 6547: 
1.801     tempelho 6548: table#LC_title_bar a {
                   6549:   color: $fontmenu;
                   6550: }
1.836     bisitz   6551: 
1.807     droeschl 6552: table#LC_title_bar {
1.819     tempelho 6553:   clear: both;
1.836     bisitz   6554:   display: none;
1.807     droeschl 6555: }
                   6556: 
1.795     www      6557: table#LC_title_bar,
1.933     droeschl 6558: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6559: table#LC_title_bar.LC_with_remote {
1.359     albertel 6560:   width: 100%;
1.392     albertel 6561:   border-color: $pgbg;
                   6562:   border-style: solid;
                   6563:   border-width: $border;
1.379     albertel 6564:   background: $pgbg;
1.801     tempelho 6565:   color: $fontmenu;
1.392     albertel 6566:   border-collapse: collapse;
1.803     bisitz   6567:   padding: 0;
1.819     tempelho 6568:   margin: 0;
1.359     albertel 6569: }
1.795     www      6570: 
1.933     droeschl 6571: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6572:     margin: 0;
                   6573:     padding: 0;
1.933     droeschl 6574:     position: relative;
                   6575:     list-style: none;
1.913     droeschl 6576: }
1.933     droeschl 6577: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6578:     display: inline;
                   6579: }
1.933     droeschl 6580: 
                   6581: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6582:     padding: 0;
1.933     droeschl 6583:     margin: 0;
                   6584:     float: left;
1.913     droeschl 6585: }
1.933     droeschl 6586: .LC_breadcrumb_tools_tools {
                   6587:     padding: 0;
                   6588:     margin: 0;
1.913     droeschl 6589:     float: right;
                   6590: }
                   6591: 
1.1240    raeburn  6592: .LC_placement_prog {
                   6593:     padding-right: 20px;
                   6594:     font-weight: bold;
                   6595:     font-size: 90%;
                   6596: }
                   6597: 
1.359     albertel 6598: table#LC_title_bar td {
                   6599:   background: $tabbg;
                   6600: }
1.795     www      6601: 
1.911     bisitz   6602: table#LC_menubuttons img {
1.803     bisitz   6603:   border: none;
1.346     albertel 6604: }
1.795     www      6605: 
1.842     droeschl 6606: .LC_breadcrumbs_component {
1.911     bisitz   6607:   float: right;
                   6608:   margin: 0 1em;
1.357     albertel 6609: }
1.842     droeschl 6610: .LC_breadcrumbs_component img {
1.911     bisitz   6611:   vertical-align: middle;
1.777     tempelho 6612: }
1.795     www      6613: 
1.1243    raeburn  6614: .LC_breadcrumbs_hoverable {
                   6615:   background: $sidebg;
                   6616: }
                   6617: 
1.383     albertel 6618: td.LC_table_cell_checkbox {
                   6619:   text-align: center;
                   6620: }
1.795     www      6621: 
                   6622: .LC_fontsize_small {
1.911     bisitz   6623:   font-size: 70%;
1.705     tempelho 6624: }
                   6625: 
1.844     bisitz   6626: #LC_breadcrumbs {
1.911     bisitz   6627:   clear:both;
                   6628:   background: $sidebg;
                   6629:   border-bottom: 1px solid $lg_border_color;
                   6630:   line-height: 2.5em;
1.933     droeschl 6631:   overflow: hidden;
1.911     bisitz   6632:   margin: 0;
                   6633:   padding: 0;
1.995     raeburn  6634:   text-align: left;
1.819     tempelho 6635: }
1.862     bisitz   6636: 
1.1098    bisitz   6637: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6638:   clear:both;
                   6639:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6640:   border: 1px solid $sidebg;
1.1098    bisitz   6641:   margin: 0 0 10px 0;
1.966     bisitz   6642:   padding: 3px;
1.995     raeburn  6643:   text-align: left;
1.822     bisitz   6644: }
                   6645: 
1.795     www      6646: .LC_fontsize_medium {
1.911     bisitz   6647:   font-size: 85%;
1.705     tempelho 6648: }
                   6649: 
1.795     www      6650: .LC_fontsize_large {
1.911     bisitz   6651:   font-size: 120%;
1.705     tempelho 6652: }
                   6653: 
1.346     albertel 6654: .LC_menubuttons_inline_text {
                   6655:   color: $font;
1.698     harmsja  6656:   font-size: 90%;
1.701     harmsja  6657:   padding-left:3px;
1.346     albertel 6658: }
                   6659: 
1.934     droeschl 6660: .LC_menubuttons_inline_text img{
                   6661:   vertical-align: middle;
                   6662: }
                   6663: 
1.1051    www      6664: li.LC_menubuttons_inline_text img {
1.951     onken    6665:   cursor:pointer;
1.1002    droeschl 6666:   text-decoration: none;
1.951     onken    6667: }
                   6668: 
1.526     www      6669: .LC_menubuttons_link {
                   6670:   text-decoration: none;
                   6671: }
1.795     www      6672: 
1.522     albertel 6673: .LC_menubuttons_category {
1.521     www      6674:   color: $font;
1.526     www      6675:   background: $pgbg;
1.521     www      6676:   font-size: larger;
                   6677:   font-weight: bold;
                   6678: }
                   6679: 
1.346     albertel 6680: td.LC_menubuttons_text {
1.911     bisitz   6681:   color: $font;
1.346     albertel 6682: }
1.706     harmsja  6683: 
1.346     albertel 6684: .LC_current_location {
                   6685:   background: $tabbg;
                   6686: }
1.795     www      6687: 
1.1286    raeburn  6688: td.LC_zero_height {
                   6689:   line-height: 0; 
                   6690:   cellpadding: 0;
                   6691: }
                   6692: 
1.938     bisitz   6693: table.LC_data_table {
1.347     albertel 6694:   border: 1px solid #000000;
1.402     albertel 6695:   border-collapse: separate;
1.426     albertel 6696:   border-spacing: 1px;
1.610     albertel 6697:   background: $pgbg;
1.347     albertel 6698: }
1.795     www      6699: 
1.422     albertel 6700: .LC_data_table_dense {
                   6701:   font-size: small;
                   6702: }
1.795     www      6703: 
1.507     raeburn  6704: table.LC_nested_outer {
                   6705:   border: 1px solid #000000;
1.589     raeburn  6706:   border-collapse: collapse;
1.803     bisitz   6707:   border-spacing: 0;
1.507     raeburn  6708:   width: 100%;
                   6709: }
1.795     www      6710: 
1.879     raeburn  6711: table.LC_innerpickbox,
1.507     raeburn  6712: table.LC_nested {
1.803     bisitz   6713:   border: none;
1.589     raeburn  6714:   border-collapse: collapse;
1.803     bisitz   6715:   border-spacing: 0;
1.507     raeburn  6716:   width: 100%;
                   6717: }
1.795     www      6718: 
1.911     bisitz   6719: table.LC_data_table tr th,
                   6720: table.LC_calendar tr th,
1.879     raeburn  6721: table.LC_prior_tries tr th,
                   6722: table.LC_innerpickbox tr th {
1.349     albertel 6723:   font-weight: bold;
                   6724:   background-color: $data_table_head;
1.801     tempelho 6725:   color:$fontmenu;
1.701     harmsja  6726:   font-size:90%;
1.347     albertel 6727: }
1.795     www      6728: 
1.879     raeburn  6729: table.LC_innerpickbox tr th,
                   6730: table.LC_innerpickbox tr td {
                   6731:   vertical-align: top;
                   6732: }
                   6733: 
1.711     raeburn  6734: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6735:   background-color: #CCCCCC;
1.711     raeburn  6736:   font-weight: bold;
                   6737:   text-align: left;
                   6738: }
1.795     www      6739: 
1.912     bisitz   6740: table.LC_data_table tr.LC_odd_row > td {
                   6741:   background-color: $data_table_light;
                   6742:   padding: 2px;
                   6743:   vertical-align: top;
                   6744: }
                   6745: 
1.809     bisitz   6746: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6747:   background-color: $data_table_light;
1.912     bisitz   6748:   vertical-align: top;
                   6749: }
                   6750: 
                   6751: table.LC_data_table tr.LC_even_row > td {
                   6752:   background-color: $data_table_dark;
1.425     albertel 6753:   padding: 2px;
1.900     bisitz   6754:   vertical-align: top;
1.347     albertel 6755: }
1.795     www      6756: 
1.809     bisitz   6757: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6758:   background-color: $data_table_dark;
1.900     bisitz   6759:   vertical-align: top;
1.347     albertel 6760: }
1.795     www      6761: 
1.425     albertel 6762: table.LC_data_table tr.LC_data_table_highlight td {
                   6763:   background-color: $data_table_darker;
                   6764: }
1.795     www      6765: 
1.639     raeburn  6766: table.LC_data_table tr td.LC_leftcol_header {
                   6767:   background-color: $data_table_head;
                   6768:   font-weight: bold;
                   6769: }
1.795     www      6770: 
1.451     albertel 6771: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6772: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6773:   font-weight: bold;
                   6774:   font-style: italic;
                   6775:   text-align: center;
                   6776:   padding: 8px;
1.347     albertel 6777: }
1.795     www      6778: 
1.1114    raeburn  6779: table.LC_data_table tr.LC_empty_row td,
                   6780: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6781:   background-color: $sidebg;
                   6782: }
                   6783: 
                   6784: table.LC_nested tr.LC_empty_row td {
                   6785:   background-color: #FFFFFF;
                   6786: }
                   6787: 
1.890     droeschl 6788: table.LC_caption {
                   6789: }
                   6790: 
1.507     raeburn  6791: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6792:   padding: 4ex
                   6793: }
1.795     www      6794: 
1.507     raeburn  6795: table.LC_nested_outer tr th {
                   6796:   font-weight: bold;
1.801     tempelho 6797:   color:$fontmenu;
1.507     raeburn  6798:   background-color: $data_table_head;
1.701     harmsja  6799:   font-size: small;
1.507     raeburn  6800:   border-bottom: 1px solid #000000;
                   6801: }
1.795     www      6802: 
1.507     raeburn  6803: table.LC_nested_outer tr td.LC_subheader {
                   6804:   background-color: $data_table_head;
                   6805:   font-weight: bold;
                   6806:   font-size: small;
                   6807:   border-bottom: 1px solid #000000;
                   6808:   text-align: right;
1.451     albertel 6809: }
1.795     www      6810: 
1.507     raeburn  6811: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6812:   background-color: #CCCCCC;
1.451     albertel 6813:   font-weight: bold;
                   6814:   font-size: small;
1.507     raeburn  6815:   text-align: center;
                   6816: }
1.795     www      6817: 
1.589     raeburn  6818: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6819: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6820:   text-align: left;
1.451     albertel 6821: }
1.795     www      6822: 
1.507     raeburn  6823: table.LC_nested td {
1.735     bisitz   6824:   background-color: #FFFFFF;
1.451     albertel 6825:   font-size: small;
1.507     raeburn  6826: }
1.795     www      6827: 
1.507     raeburn  6828: table.LC_nested_outer tr th.LC_right_item,
                   6829: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6830: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6831: table.LC_nested tr td.LC_right_item {
1.451     albertel 6832:   text-align: right;
                   6833: }
                   6834: 
1.507     raeburn  6835: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6836:   background-color: #EEEEEE;
1.451     albertel 6837: }
                   6838: 
1.473     raeburn  6839: table.LC_createuser {
                   6840: }
                   6841: 
                   6842: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6843:   font-size: small;
1.473     raeburn  6844: }
                   6845: 
                   6846: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6847:   background-color: #CCCCCC;
1.473     raeburn  6848:   font-weight: bold;
                   6849:   text-align: center;
                   6850: }
                   6851: 
1.349     albertel 6852: table.LC_calendar {
                   6853:   border: 1px solid #000000;
                   6854:   border-collapse: collapse;
1.917     raeburn  6855:   width: 98%;
1.349     albertel 6856: }
1.795     www      6857: 
1.349     albertel 6858: table.LC_calendar_pickdate {
                   6859:   font-size: xx-small;
                   6860: }
1.795     www      6861: 
1.349     albertel 6862: table.LC_calendar tr td {
                   6863:   border: 1px solid #000000;
                   6864:   vertical-align: top;
1.917     raeburn  6865:   width: 14%;
1.349     albertel 6866: }
1.795     www      6867: 
1.349     albertel 6868: table.LC_calendar tr td.LC_calendar_day_empty {
                   6869:   background-color: $data_table_dark;
                   6870: }
1.795     www      6871: 
1.779     bisitz   6872: table.LC_calendar tr td.LC_calendar_day_current {
                   6873:   background-color: $data_table_highlight;
1.777     tempelho 6874: }
1.795     www      6875: 
1.938     bisitz   6876: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6877:   background-color: $mail_new;
                   6878: }
1.795     www      6879: 
1.938     bisitz   6880: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6881:   background-color: $mail_new_hover;
                   6882: }
1.795     www      6883: 
1.938     bisitz   6884: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6885:   background-color: $mail_read;
                   6886: }
1.795     www      6887: 
1.938     bisitz   6888: /*
                   6889: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6890:   background-color: $mail_read_hover;
                   6891: }
1.938     bisitz   6892: */
1.795     www      6893: 
1.938     bisitz   6894: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6895:   background-color: $mail_replied;
                   6896: }
1.795     www      6897: 
1.938     bisitz   6898: /*
                   6899: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6900:   background-color: $mail_replied_hover;
                   6901: }
1.938     bisitz   6902: */
1.795     www      6903: 
1.938     bisitz   6904: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6905:   background-color: $mail_other;
                   6906: }
1.795     www      6907: 
1.938     bisitz   6908: /*
                   6909: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6910:   background-color: $mail_other_hover;
                   6911: }
1.938     bisitz   6912: */
1.494     raeburn  6913: 
1.777     tempelho 6914: table.LC_data_table tr > td.LC_browser_file,
                   6915: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6916:   background: #AAEE77;
1.389     albertel 6917: }
1.795     www      6918: 
1.777     tempelho 6919: table.LC_data_table tr > td.LC_browser_file_locked,
                   6920: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6921:   background: #FFAA99;
1.387     albertel 6922: }
1.795     www      6923: 
1.777     tempelho 6924: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6925:   background: #888888;
1.779     bisitz   6926: }
1.795     www      6927: 
1.777     tempelho 6928: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6929: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6930:   background: #F8F866;
1.777     tempelho 6931: }
1.795     www      6932: 
1.696     bisitz   6933: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6934:   background: #E0E8FF;
1.387     albertel 6935: }
1.696     bisitz   6936: 
1.707     bisitz   6937: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6938:   /* background: #77FF77; */
1.707     bisitz   6939: }
1.795     www      6940: 
1.707     bisitz   6941: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6942:   border-right: 8px solid #FFFF77;
1.707     bisitz   6943: }
1.795     www      6944: 
1.707     bisitz   6945: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6946:   border-right: 8px solid #FFAA77;
1.707     bisitz   6947: }
1.795     www      6948: 
1.707     bisitz   6949: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6950:   border-right: 8px solid #FF7777;
1.707     bisitz   6951: }
1.795     www      6952: 
1.707     bisitz   6953: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6954:   border-right: 8px solid #AAFF77;
1.707     bisitz   6955: }
1.795     www      6956: 
1.707     bisitz   6957: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6958:   border-right: 8px solid #11CC55;
1.707     bisitz   6959: }
                   6960: 
1.388     albertel 6961: span.LC_current_location {
1.701     harmsja  6962:   font-size:larger;
1.388     albertel 6963:   background: $pgbg;
                   6964: }
1.387     albertel 6965: 
1.1029    www      6966: span.LC_current_nav_location {
                   6967:   font-weight:bold;
                   6968:   background: $sidebg;
                   6969: }
                   6970: 
1.395     albertel 6971: span.LC_parm_menu_item {
                   6972:   font-size: larger;
                   6973: }
1.795     www      6974: 
1.395     albertel 6975: span.LC_parm_scope_all {
                   6976:   color: red;
                   6977: }
1.795     www      6978: 
1.395     albertel 6979: span.LC_parm_scope_folder {
                   6980:   color: green;
                   6981: }
1.795     www      6982: 
1.395     albertel 6983: span.LC_parm_scope_resource {
                   6984:   color: orange;
                   6985: }
1.795     www      6986: 
1.395     albertel 6987: span.LC_parm_part {
                   6988:   color: blue;
                   6989: }
1.795     www      6990: 
1.911     bisitz   6991: span.LC_parm_folder,
                   6992: span.LC_parm_symb {
1.395     albertel 6993:   font-size: x-small;
                   6994:   font-family: $mono;
                   6995:   color: #AAAAAA;
                   6996: }
                   6997: 
1.977     bisitz   6998: ul.LC_parm_parmlist li {
                   6999:   display: inline-block;
                   7000:   padding: 0.3em 0.8em;
                   7001:   vertical-align: top;
                   7002:   width: 150px;
                   7003:   border-top:1px solid $lg_border_color;
                   7004: }
                   7005: 
1.795     www      7006: td.LC_parm_overview_level_menu,
                   7007: td.LC_parm_overview_map_menu,
                   7008: td.LC_parm_overview_parm_selectors,
                   7009: td.LC_parm_overview_restrictions  {
1.396     albertel 7010:   border: 1px solid black;
                   7011:   border-collapse: collapse;
                   7012: }
1.795     www      7013: 
1.1285    raeburn  7014: span.LC_parm_recursive,
                   7015: td.LC_parm_recursive {
                   7016:   font-weight: bold;
                   7017:   font-size: smaller;
                   7018: }
                   7019: 
1.396     albertel 7020: table.LC_parm_overview_restrictions td {
                   7021:   border-width: 1px 4px 1px 4px;
                   7022:   border-style: solid;
                   7023:   border-color: $pgbg;
                   7024:   text-align: center;
                   7025: }
1.795     www      7026: 
1.396     albertel 7027: table.LC_parm_overview_restrictions th {
                   7028:   background: $tabbg;
                   7029:   border-width: 1px 4px 1px 4px;
                   7030:   border-style: solid;
                   7031:   border-color: $pgbg;
                   7032: }
1.795     www      7033: 
1.398     albertel 7034: table#LC_helpmenu {
1.803     bisitz   7035:   border: none;
1.398     albertel 7036:   height: 55px;
1.803     bisitz   7037:   border-spacing: 0;
1.398     albertel 7038: }
                   7039: 
                   7040: table#LC_helpmenu fieldset legend {
                   7041:   font-size: larger;
                   7042: }
1.795     www      7043: 
1.397     albertel 7044: table#LC_helpmenu_links {
                   7045:   width: 100%;
                   7046:   border: 1px solid black;
                   7047:   background: $pgbg;
1.803     bisitz   7048:   padding: 0;
1.397     albertel 7049:   border-spacing: 1px;
                   7050: }
1.795     www      7051: 
1.397     albertel 7052: table#LC_helpmenu_links tr td {
                   7053:   padding: 1px;
                   7054:   background: $tabbg;
1.399     albertel 7055:   text-align: center;
                   7056:   font-weight: bold;
1.397     albertel 7057: }
1.396     albertel 7058: 
1.795     www      7059: table#LC_helpmenu_links a:link,
                   7060: table#LC_helpmenu_links a:visited,
1.397     albertel 7061: table#LC_helpmenu_links a:active {
                   7062:   text-decoration: none;
                   7063:   color: $font;
                   7064: }
1.795     www      7065: 
1.397     albertel 7066: table#LC_helpmenu_links a:hover {
                   7067:   text-decoration: underline;
                   7068:   color: $vlink;
                   7069: }
1.396     albertel 7070: 
1.417     albertel 7071: .LC_chrt_popup_exists {
                   7072:   border: 1px solid #339933;
                   7073:   margin: -1px;
                   7074: }
1.795     www      7075: 
1.417     albertel 7076: .LC_chrt_popup_up {
                   7077:   border: 1px solid yellow;
                   7078:   margin: -1px;
                   7079: }
1.795     www      7080: 
1.417     albertel 7081: .LC_chrt_popup {
                   7082:   border: 1px solid #8888FF;
                   7083:   background: #CCCCFF;
                   7084: }
1.795     www      7085: 
1.421     albertel 7086: table.LC_pick_box {
                   7087:   border-collapse: separate;
                   7088:   background: white;
                   7089:   border: 1px solid black;
                   7090:   border-spacing: 1px;
                   7091: }
1.795     www      7092: 
1.421     albertel 7093: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7094:   background: $sidebg;
1.421     albertel 7095:   font-weight: bold;
1.900     bisitz   7096:   text-align: left;
1.740     bisitz   7097:   vertical-align: top;
1.421     albertel 7098:   width: 184px;
                   7099:   padding: 8px;
                   7100: }
1.795     www      7101: 
1.579     raeburn  7102: table.LC_pick_box td.LC_pick_box_value {
                   7103:   text-align: left;
                   7104:   padding: 8px;
                   7105: }
1.795     www      7106: 
1.579     raeburn  7107: table.LC_pick_box td.LC_pick_box_select {
                   7108:   text-align: left;
                   7109:   padding: 8px;
                   7110: }
1.795     www      7111: 
1.424     albertel 7112: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7113:   padding: 0;
1.421     albertel 7114:   height: 1px;
                   7115:   background: black;
                   7116: }
1.795     www      7117: 
1.421     albertel 7118: table.LC_pick_box td.LC_pick_box_submit {
                   7119:   text-align: right;
                   7120: }
1.795     www      7121: 
1.579     raeburn  7122: table.LC_pick_box td.LC_evenrow_value {
                   7123:   text-align: left;
                   7124:   padding: 8px;
                   7125:   background-color: $data_table_light;
                   7126: }
1.795     www      7127: 
1.579     raeburn  7128: table.LC_pick_box td.LC_oddrow_value {
                   7129:   text-align: left;
                   7130:   padding: 8px;
                   7131:   background-color: $data_table_light;
                   7132: }
1.795     www      7133: 
1.579     raeburn  7134: span.LC_helpform_receipt_cat {
                   7135:   font-weight: bold;
                   7136: }
1.795     www      7137: 
1.424     albertel 7138: table.LC_group_priv_box {
                   7139:   background: white;
                   7140:   border: 1px solid black;
                   7141:   border-spacing: 1px;
                   7142: }
1.795     www      7143: 
1.424     albertel 7144: table.LC_group_priv_box td.LC_pick_box_title {
                   7145:   background: $tabbg;
                   7146:   font-weight: bold;
                   7147:   text-align: right;
                   7148:   width: 184px;
                   7149: }
1.795     www      7150: 
1.424     albertel 7151: table.LC_group_priv_box td.LC_groups_fixed {
                   7152:   background: $data_table_light;
                   7153:   text-align: center;
                   7154: }
1.795     www      7155: 
1.424     albertel 7156: table.LC_group_priv_box td.LC_groups_optional {
                   7157:   background: $data_table_dark;
                   7158:   text-align: center;
                   7159: }
1.795     www      7160: 
1.424     albertel 7161: table.LC_group_priv_box td.LC_groups_functionality {
                   7162:   background: $data_table_darker;
                   7163:   text-align: center;
                   7164:   font-weight: bold;
                   7165: }
1.795     www      7166: 
1.424     albertel 7167: table.LC_group_priv td {
                   7168:   text-align: left;
1.803     bisitz   7169:   padding: 0;
1.424     albertel 7170: }
                   7171: 
                   7172: .LC_navbuttons {
                   7173:   margin: 2ex 0ex 2ex 0ex;
                   7174: }
1.795     www      7175: 
1.423     albertel 7176: .LC_topic_bar {
                   7177:   font-weight: bold;
                   7178:   background: $tabbg;
1.918     wenzelju 7179:   margin: 1em 0em 1em 2em;
1.805     bisitz   7180:   padding: 3px;
1.918     wenzelju 7181:   font-size: 1.2em;
1.423     albertel 7182: }
1.795     www      7183: 
1.423     albertel 7184: .LC_topic_bar span {
1.918     wenzelju 7185:   left: 0.5em;
                   7186:   position: absolute;
1.423     albertel 7187:   vertical-align: middle;
1.918     wenzelju 7188:   font-size: 1.2em;
1.423     albertel 7189: }
1.795     www      7190: 
1.423     albertel 7191: table.LC_course_group_status {
                   7192:   margin: 20px;
                   7193: }
1.795     www      7194: 
1.423     albertel 7195: table.LC_status_selector td {
                   7196:   vertical-align: top;
                   7197:   text-align: center;
1.424     albertel 7198:   padding: 4px;
                   7199: }
1.795     www      7200: 
1.599     albertel 7201: div.LC_feedback_link {
1.616     albertel 7202:   clear: both;
1.829     kalberla 7203:   background: $sidebg;
1.779     bisitz   7204:   width: 100%;
1.829     kalberla 7205:   padding-bottom: 10px;
                   7206:   border: 1px $tabbg solid;
1.833     kalberla 7207:   height: 22px;
                   7208:   line-height: 22px;
                   7209:   padding-top: 5px;
                   7210: }
                   7211: 
                   7212: div.LC_feedback_link img {
                   7213:   height: 22px;
1.867     kalberla 7214:   vertical-align:middle;
1.829     kalberla 7215: }
                   7216: 
1.911     bisitz   7217: div.LC_feedback_link a {
1.829     kalberla 7218:   text-decoration: none;
1.489     raeburn  7219: }
1.795     www      7220: 
1.867     kalberla 7221: div.LC_comblock {
1.911     bisitz   7222:   display:inline;
1.867     kalberla 7223:   color:$font;
                   7224:   font-size:90%;
                   7225: }
                   7226: 
                   7227: div.LC_feedback_link div.LC_comblock {
                   7228:   padding-left:5px;
                   7229: }
                   7230: 
                   7231: div.LC_feedback_link div.LC_comblock a {
                   7232:   color:$font;
                   7233: }
                   7234: 
1.489     raeburn  7235: span.LC_feedback_link {
1.858     bisitz   7236:   /* background: $feedback_link_bg; */
1.599     albertel 7237:   font-size: larger;
                   7238: }
1.795     www      7239: 
1.599     albertel 7240: span.LC_message_link {
1.858     bisitz   7241:   /* background: $feedback_link_bg; */
1.599     albertel 7242:   font-size: larger;
                   7243:   position: absolute;
                   7244:   right: 1em;
1.489     raeburn  7245: }
1.421     albertel 7246: 
1.515     albertel 7247: table.LC_prior_tries {
1.524     albertel 7248:   border: 1px solid #000000;
                   7249:   border-collapse: separate;
                   7250:   border-spacing: 1px;
1.515     albertel 7251: }
1.523     albertel 7252: 
1.515     albertel 7253: table.LC_prior_tries td {
1.524     albertel 7254:   padding: 2px;
1.515     albertel 7255: }
1.523     albertel 7256: 
                   7257: .LC_answer_correct {
1.795     www      7258:   background: lightgreen;
                   7259:   color: darkgreen;
                   7260:   padding: 6px;
1.523     albertel 7261: }
1.795     www      7262: 
1.523     albertel 7263: .LC_answer_charged_try {
1.797     www      7264:   background: #FFAAAA;
1.795     www      7265:   color: darkred;
                   7266:   padding: 6px;
1.523     albertel 7267: }
1.795     www      7268: 
1.779     bisitz   7269: .LC_answer_not_charged_try,
1.523     albertel 7270: .LC_answer_no_grade,
                   7271: .LC_answer_late {
1.795     www      7272:   background: lightyellow;
1.523     albertel 7273:   color: black;
1.795     www      7274:   padding: 6px;
1.523     albertel 7275: }
1.795     www      7276: 
1.523     albertel 7277: .LC_answer_previous {
1.795     www      7278:   background: lightblue;
                   7279:   color: darkblue;
                   7280:   padding: 6px;
1.523     albertel 7281: }
1.795     www      7282: 
1.779     bisitz   7283: .LC_answer_no_message {
1.777     tempelho 7284:   background: #FFFFFF;
                   7285:   color: black;
1.795     www      7286:   padding: 6px;
1.779     bisitz   7287: }
1.795     www      7288: 
1.1334    raeburn  7289: .LC_answer_unknown,
                   7290: .LC_answer_warning {
1.779     bisitz   7291:   background: orange;
                   7292:   color: black;
1.795     www      7293:   padding: 6px;
1.777     tempelho 7294: }
1.795     www      7295: 
1.529     albertel 7296: span.LC_prior_numerical,
                   7297: span.LC_prior_string,
                   7298: span.LC_prior_custom,
                   7299: span.LC_prior_reaction,
                   7300: span.LC_prior_math {
1.925     bisitz   7301:   font-family: $mono;
1.523     albertel 7302:   white-space: pre;
                   7303: }
                   7304: 
1.525     albertel 7305: span.LC_prior_string {
1.925     bisitz   7306:   font-family: $mono;
1.525     albertel 7307:   white-space: pre;
                   7308: }
                   7309: 
1.523     albertel 7310: table.LC_prior_option {
                   7311:   width: 100%;
                   7312:   border-collapse: collapse;
                   7313: }
1.795     www      7314: 
1.911     bisitz   7315: table.LC_prior_rank,
1.795     www      7316: table.LC_prior_match {
1.528     albertel 7317:   border-collapse: collapse;
                   7318: }
1.795     www      7319: 
1.528     albertel 7320: table.LC_prior_option tr td,
                   7321: table.LC_prior_rank tr td,
                   7322: table.LC_prior_match tr td {
1.524     albertel 7323:   border: 1px solid #000000;
1.515     albertel 7324: }
                   7325: 
1.855     bisitz   7326: .LC_nobreak {
1.544     albertel 7327:   white-space: nowrap;
1.519     raeburn  7328: }
                   7329: 
1.576     raeburn  7330: span.LC_cusr_emph {
                   7331:   font-style: italic;
                   7332: }
                   7333: 
1.633     raeburn  7334: span.LC_cusr_subheading {
                   7335:   font-weight: normal;
                   7336:   font-size: 85%;
                   7337: }
                   7338: 
1.861     bisitz   7339: div.LC_docs_entry_move {
1.859     bisitz   7340:   border: 1px solid #BBBBBB;
1.545     albertel 7341:   background: #DDDDDD;
1.861     bisitz   7342:   width: 22px;
1.859     bisitz   7343:   padding: 1px;
                   7344:   margin: 0;
1.545     albertel 7345: }
                   7346: 
1.861     bisitz   7347: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7348: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7349:   font-size: x-small;
                   7350: }
1.795     www      7351: 
1.861     bisitz   7352: .LC_docs_entry_parameter {
                   7353:   white-space: nowrap;
                   7354: }
                   7355: 
1.544     albertel 7356: .LC_docs_copy {
1.545     albertel 7357:   color: #000099;
1.544     albertel 7358: }
1.795     www      7359: 
1.544     albertel 7360: .LC_docs_cut {
1.545     albertel 7361:   color: #550044;
1.544     albertel 7362: }
1.795     www      7363: 
1.544     albertel 7364: .LC_docs_rename {
1.545     albertel 7365:   color: #009900;
1.544     albertel 7366: }
1.795     www      7367: 
1.544     albertel 7368: .LC_docs_remove {
1.545     albertel 7369:   color: #990000;
                   7370: }
                   7371: 
1.1284    raeburn  7372: .LC_docs_alias {
                   7373:   color: #440055;  
                   7374: }
                   7375: 
1.1286    raeburn  7376: .LC_domprefs_email,
1.1284    raeburn  7377: .LC_docs_alias_name,
1.547     albertel 7378: .LC_docs_reinit_warn,
                   7379: .LC_docs_ext_edit {
                   7380:   font-size: x-small;
                   7381: }
                   7382: 
1.545     albertel 7383: table.LC_docs_adddocs td,
                   7384: table.LC_docs_adddocs th {
                   7385:   border: 1px solid #BBBBBB;
                   7386:   padding: 4px;
                   7387:   background: #DDDDDD;
1.543     albertel 7388: }
                   7389: 
1.584     albertel 7390: table.LC_sty_begin {
                   7391:   background: #BBFFBB;
                   7392: }
1.795     www      7393: 
1.584     albertel 7394: table.LC_sty_end {
                   7395:   background: #FFBBBB;
                   7396: }
                   7397: 
1.589     raeburn  7398: table.LC_double_column {
1.803     bisitz   7399:   border-width: 0;
1.589     raeburn  7400:   border-collapse: collapse;
                   7401:   width: 100%;
                   7402:   padding: 2px;
                   7403: }
                   7404: 
                   7405: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7406:   top: 2px;
1.589     raeburn  7407:   left: 2px;
                   7408:   width: 47%;
                   7409:   vertical-align: top;
                   7410: }
                   7411: 
                   7412: table.LC_double_column tr td.LC_right_col {
                   7413:   top: 2px;
1.779     bisitz   7414:   right: 2px;
1.589     raeburn  7415:   width: 47%;
                   7416:   vertical-align: top;
                   7417: }
                   7418: 
1.591     raeburn  7419: div.LC_left_float {
                   7420:   float: left;
                   7421:   padding-right: 5%;
1.597     albertel 7422:   padding-bottom: 4px;
1.591     raeburn  7423: }
                   7424: 
                   7425: div.LC_clear_float_header {
1.597     albertel 7426:   padding-bottom: 2px;
1.591     raeburn  7427: }
                   7428: 
                   7429: div.LC_clear_float_footer {
1.597     albertel 7430:   padding-top: 10px;
1.591     raeburn  7431:   clear: both;
                   7432: }
                   7433: 
1.597     albertel 7434: div.LC_grade_show_user {
1.941     bisitz   7435: /*  border-left: 5px solid $sidebg; */
                   7436:   border-top: 5px solid #000000;
                   7437:   margin: 50px 0 0 0;
1.936     bisitz   7438:   padding: 15px 0 5px 10px;
1.597     albertel 7439: }
1.795     www      7440: 
1.936     bisitz   7441: div.LC_grade_show_user_odd_row {
1.941     bisitz   7442: /*  border-left: 5px solid #000000; */
                   7443: }
                   7444: 
                   7445: div.LC_grade_show_user div.LC_Box {
                   7446:   margin-right: 50px;
1.597     albertel 7447: }
                   7448: 
                   7449: div.LC_grade_submissions,
                   7450: div.LC_grade_message_center,
1.936     bisitz   7451: div.LC_grade_info_links {
1.597     albertel 7452:   margin: 5px;
                   7453:   width: 99%;
                   7454:   background: #FFFFFF;
                   7455: }
1.795     www      7456: 
1.597     albertel 7457: div.LC_grade_submissions_header,
1.936     bisitz   7458: div.LC_grade_message_center_header {
1.705     tempelho 7459:   font-weight: bold;
                   7460:   font-size: large;
1.597     albertel 7461: }
1.795     www      7462: 
1.597     albertel 7463: div.LC_grade_submissions_body,
1.936     bisitz   7464: div.LC_grade_message_center_body {
1.597     albertel 7465:   border: 1px solid black;
                   7466:   width: 99%;
                   7467:   background: #FFFFFF;
                   7468: }
1.795     www      7469: 
1.613     albertel 7470: table.LC_scantron_action {
                   7471:   width: 100%;
                   7472: }
1.795     www      7473: 
1.613     albertel 7474: table.LC_scantron_action tr th {
1.698     harmsja  7475:   font-weight:bold;
                   7476:   font-style:normal;
1.613     albertel 7477: }
1.795     www      7478: 
1.779     bisitz   7479: .LC_edit_problem_header,
1.614     albertel 7480: div.LC_edit_problem_footer {
1.705     tempelho 7481:   font-weight: normal;
                   7482:   font-size:  medium;
1.602     albertel 7483:   margin: 2px;
1.1060    bisitz   7484:   background-color: $sidebg;
1.600     albertel 7485: }
1.795     www      7486: 
1.600     albertel 7487: div.LC_edit_problem_header,
1.602     albertel 7488: div.LC_edit_problem_header div,
1.614     albertel 7489: div.LC_edit_problem_footer,
                   7490: div.LC_edit_problem_footer div,
1.602     albertel 7491: div.LC_edit_problem_editxml_header,
                   7492: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7493:   z-index: 100;
1.600     albertel 7494: }
1.795     www      7495: 
1.600     albertel 7496: div.LC_edit_problem_header_title {
1.705     tempelho 7497:   font-weight: bold;
                   7498:   font-size: larger;
1.602     albertel 7499:   background: $tabbg;
                   7500:   padding: 3px;
1.1060    bisitz   7501:   margin: 0 0 5px 0;
1.602     albertel 7502: }
1.795     www      7503: 
1.602     albertel 7504: table.LC_edit_problem_header_title {
                   7505:   width: 100%;
1.600     albertel 7506:   background: $tabbg;
1.602     albertel 7507: }
                   7508: 
1.1205    golterma 7509: div.LC_edit_actionbar {
                   7510:     background-color: $sidebg;
1.1218    droeschl 7511:     margin: 0;
                   7512:     padding: 0;
                   7513:     line-height: 200%;
1.602     albertel 7514: }
1.795     www      7515: 
1.1218    droeschl 7516: div.LC_edit_actionbar div{
                   7517:     padding: 0;
                   7518:     margin: 0;
                   7519:     display: inline-block;
1.600     albertel 7520: }
1.795     www      7521: 
1.1124    bisitz   7522: .LC_edit_opt {
                   7523:   padding-left: 1em;
                   7524:   white-space: nowrap;
                   7525: }
                   7526: 
1.1152    golterma 7527: .LC_edit_problem_latexhelper{
                   7528:     text-align: right;
                   7529: }
                   7530: 
                   7531: #LC_edit_problem_colorful div{
                   7532:     margin-left: 40px;
                   7533: }
                   7534: 
1.1205    golterma 7535: #LC_edit_problem_codemirror div{
                   7536:     margin-left: 0px;
                   7537: }
                   7538: 
1.911     bisitz   7539: img.stift {
1.803     bisitz   7540:   border-width: 0;
                   7541:   vertical-align: middle;
1.677     riegler  7542: }
1.680     riegler  7543: 
1.923     bisitz   7544: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7545:   vertical-align: top;
1.777     tempelho 7546: }
1.795     www      7547: 
1.716     raeburn  7548: div.LC_createcourse {
1.911     bisitz   7549:   margin: 10px 10px 10px 10px;
1.716     raeburn  7550: }
                   7551: 
1.917     raeburn  7552: .LC_dccid {
1.1130    raeburn  7553:   float: right;
1.917     raeburn  7554:   margin: 0.2em 0 0 0;
                   7555:   padding: 0;
                   7556:   font-size: 90%;
                   7557:   display:none;
                   7558: }
                   7559: 
1.897     wenzelju 7560: ol.LC_primary_menu a:hover,
1.721     harmsja  7561: ol#LC_MenuBreadcrumbs a:hover,
                   7562: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7563: ul#LC_secondary_menu a:hover,
1.721     harmsja  7564: .LC_FormSectionClearButton input:hover
1.795     www      7565: ul.LC_TabContent   li:hover a {
1.952     onken    7566:   color:$button_hover;
1.911     bisitz   7567:   text-decoration:none;
1.693     droeschl 7568: }
                   7569: 
1.779     bisitz   7570: h1 {
1.911     bisitz   7571:   padding: 0;
                   7572:   line-height:130%;
1.693     droeschl 7573: }
1.698     harmsja  7574: 
1.911     bisitz   7575: h2,
                   7576: h3,
                   7577: h4,
                   7578: h5,
                   7579: h6 {
                   7580:   margin: 5px 0 5px 0;
                   7581:   padding: 0;
                   7582:   line-height:130%;
1.693     droeschl 7583: }
1.795     www      7584: 
                   7585: .LC_hcell {
1.911     bisitz   7586:   padding:3px 15px 3px 15px;
                   7587:   margin: 0;
                   7588:   background-color:$tabbg;
                   7589:   color:$fontmenu;
                   7590:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7591: }
1.795     www      7592: 
1.840     bisitz   7593: .LC_Box > .LC_hcell {
1.911     bisitz   7594:   margin: 0 -10px 10px -10px;
1.835     bisitz   7595: }
                   7596: 
1.721     harmsja  7597: .LC_noBorder {
1.911     bisitz   7598:   border: 0;
1.698     harmsja  7599: }
1.693     droeschl 7600: 
1.721     harmsja  7601: .LC_FormSectionClearButton input {
1.911     bisitz   7602:   background-color:transparent;
                   7603:   border: none;
                   7604:   cursor:pointer;
                   7605:   text-decoration:underline;
1.693     droeschl 7606: }
1.763     bisitz   7607: 
                   7608: .LC_help_open_topic {
1.911     bisitz   7609:   color: #FFFFFF;
                   7610:   background-color: #EEEEFF;
                   7611:   margin: 1px;
                   7612:   padding: 4px;
                   7613:   border: 1px solid #000033;
                   7614:   white-space: nowrap;
                   7615:   /* vertical-align: middle; */
1.759     neumanie 7616: }
1.693     droeschl 7617: 
1.911     bisitz   7618: dl,
                   7619: ul,
                   7620: div,
                   7621: fieldset {
                   7622:   margin: 10px 10px 10px 0;
                   7623:   /* overflow: hidden; */
1.693     droeschl 7624: }
1.795     www      7625: 
1.1211    raeburn  7626: article.geogebraweb div {
                   7627:     margin: 0;
                   7628: }
                   7629: 
1.838     bisitz   7630: fieldset > legend {
1.911     bisitz   7631:   font-weight: bold;
                   7632:   padding: 0 5px 0 5px;
1.838     bisitz   7633: }
                   7634: 
1.813     bisitz   7635: #LC_nav_bar {
1.911     bisitz   7636:   float: left;
1.995     raeburn  7637:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7638:   margin: 0 0 2px 0;
1.807     droeschl 7639: }
                   7640: 
1.916     droeschl 7641: #LC_realm {
                   7642:   margin: 0.2em 0 0 0;
                   7643:   padding: 0;
                   7644:   font-weight: bold;
                   7645:   text-align: center;
1.995     raeburn  7646:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7647: }
                   7648: 
1.911     bisitz   7649: #LC_nav_bar em {
                   7650:   font-weight: bold;
                   7651:   font-style: normal;
1.807     droeschl 7652: }
                   7653: 
1.897     wenzelju 7654: ol.LC_primary_menu {
1.934     droeschl 7655:   margin: 0;
1.1076    raeburn  7656:   padding: 0;
1.807     droeschl 7657: }
                   7658: 
1.852     droeschl 7659: ol#LC_PathBreadcrumbs {
1.911     bisitz   7660:   margin: 0;
1.693     droeschl 7661: }
                   7662: 
1.897     wenzelju 7663: ol.LC_primary_menu li {
1.1076    raeburn  7664:   color: RGB(80, 80, 80);
                   7665:   vertical-align: middle;
                   7666:   text-align: left;
                   7667:   list-style: none;
1.1205    golterma 7668:   position: relative;
1.1076    raeburn  7669:   float: left;
1.1205    golterma 7670:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7671:   line-height: 1.5em;
1.1076    raeburn  7672: }
                   7673: 
1.1205    golterma 7674: ol.LC_primary_menu li a,
                   7675: ol.LC_primary_menu li p {
1.1076    raeburn  7676:   display: block;
                   7677:   margin: 0;
                   7678:   padding: 0 5px 0 10px;
                   7679:   text-decoration: none;
                   7680: }
                   7681: 
1.1205    golterma 7682: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7683:   display: inline-block;
                   7684:   width: 95%;
                   7685:   text-align: left;
                   7686: }
                   7687: 
                   7688: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7689:   display: inline-block;	
                   7690:   width: 5%;
                   7691:   float: right;
                   7692:   text-align: right;
                   7693:   font-size: 70%;
                   7694: }
                   7695: 
                   7696: ol.LC_primary_menu ul {
1.1076    raeburn  7697:   display: none;
1.1205    golterma 7698:   width: 15em;
1.1076    raeburn  7699:   background-color: $data_table_light;
1.1205    golterma 7700:   position: absolute;
                   7701:   top: 100%;
1.1076    raeburn  7702: }
                   7703: 
1.1205    golterma 7704: ol.LC_primary_menu ul ul {
                   7705:   left: 100%;
                   7706:   top: 0;
                   7707: }
                   7708: 
                   7709: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7710:   display: block;
                   7711:   position: absolute;
                   7712:   margin: 0;
                   7713:   padding: 0;
1.1078    raeburn  7714:   z-index: 2;
1.1076    raeburn  7715: }
                   7716: 
                   7717: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7718: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7719:   font-size: 90%;
1.911     bisitz   7720:   vertical-align: top;
1.1076    raeburn  7721:   float: none;
1.1079    raeburn  7722:   border-left: 1px solid black;
                   7723:   border-right: 1px solid black;
1.1205    golterma 7724: /* A dark bottom border to visualize different menu options; 
                   7725: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7726:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7727: }
                   7728: 
1.1205    golterma 7729: ol.LC_primary_menu li li p:hover {
                   7730:   color:$button_hover;
                   7731:   text-decoration:none;
                   7732:   background-color:$data_table_dark;
1.1076    raeburn  7733: }
                   7734: 
                   7735: ol.LC_primary_menu li li a:hover {
                   7736:    color:$button_hover;
                   7737:    background-color:$data_table_dark;
1.693     droeschl 7738: }
                   7739: 
1.1205    golterma 7740: /* Font-size equal to the size of the predecessors*/
                   7741: ol.LC_primary_menu li:hover li li {
                   7742:   font-size: 100%;
                   7743: }
                   7744: 
1.897     wenzelju 7745: ol.LC_primary_menu li img {
1.911     bisitz   7746:   vertical-align: bottom;
1.934     droeschl 7747:   height: 1.1em;
1.1077    raeburn  7748:   margin: 0.2em 0 0 0;
1.693     droeschl 7749: }
                   7750: 
1.897     wenzelju 7751: ol.LC_primary_menu a {
1.911     bisitz   7752:   color: RGB(80, 80, 80);
                   7753:   text-decoration: none;
1.693     droeschl 7754: }
1.795     www      7755: 
1.949     droeschl 7756: ol.LC_primary_menu a.LC_new_message {
                   7757:   font-weight:bold;
                   7758:   color: darkred;
                   7759: }
                   7760: 
1.975     raeburn  7761: ol.LC_docs_parameters {
                   7762:   margin-left: 0;
                   7763:   padding: 0;
                   7764:   list-style: none;
                   7765: }
                   7766: 
                   7767: ol.LC_docs_parameters li {
                   7768:   margin: 0;
                   7769:   padding-right: 20px;
                   7770:   display: inline;
                   7771: }
                   7772: 
1.976     raeburn  7773: ol.LC_docs_parameters li:before {
                   7774:   content: "\\002022 \\0020";
                   7775: }
                   7776: 
                   7777: li.LC_docs_parameters_title {
                   7778:   font-weight: bold;
                   7779: }
                   7780: 
                   7781: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7782:   content: "";
                   7783: }
                   7784: 
1.897     wenzelju 7785: ul#LC_secondary_menu {
1.1107    raeburn  7786:   clear: right;
1.911     bisitz   7787:   color: $fontmenu;
                   7788:   background: $tabbg;
                   7789:   list-style: none;
                   7790:   padding: 0;
                   7791:   margin: 0;
                   7792:   width: 100%;
1.995     raeburn  7793:   text-align: left;
1.1107    raeburn  7794:   float: left;
1.808     droeschl 7795: }
                   7796: 
1.897     wenzelju 7797: ul#LC_secondary_menu li {
1.911     bisitz   7798:   font-weight: bold;
                   7799:   line-height: 1.8em;
1.1107    raeburn  7800:   border-right: 1px solid black;
                   7801:   float: left;
                   7802: }
                   7803: 
                   7804: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7805:   background-color: $data_table_light;
                   7806: }
                   7807: 
                   7808: ul#LC_secondary_menu li a {
1.911     bisitz   7809:   padding: 0 0.8em;
1.1107    raeburn  7810: }
                   7811: 
                   7812: ul#LC_secondary_menu li ul {
                   7813:   display: none;
                   7814: }
                   7815: 
                   7816: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7817:   display: block;
                   7818:   position: absolute;
                   7819:   margin: 0;
                   7820:   padding: 0;
                   7821:   list-style:none;
                   7822:   float: none;
                   7823:   background-color: $data_table_light;
                   7824:   z-index: 2;
                   7825:   margin-left: -1px;
                   7826: }
                   7827: 
                   7828: ul#LC_secondary_menu li ul li {
                   7829:   font-size: 90%;
                   7830:   vertical-align: top;
                   7831:   border-left: 1px solid black;
1.911     bisitz   7832:   border-right: 1px solid black;
1.1119    raeburn  7833:   background-color: $data_table_light;
1.1107    raeburn  7834:   list-style:none;
                   7835:   float: none;
                   7836: }
                   7837: 
                   7838: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7839:   background-color: $data_table_dark;
1.807     droeschl 7840: }
                   7841: 
1.847     tempelho 7842: ul.LC_TabContent {
1.911     bisitz   7843:   display:block;
                   7844:   background: $sidebg;
                   7845:   border-bottom: solid 1px $lg_border_color;
                   7846:   list-style:none;
1.1020    raeburn  7847:   margin: -1px -10px 0 -10px;
1.911     bisitz   7848:   padding: 0;
1.693     droeschl 7849: }
                   7850: 
1.795     www      7851: ul.LC_TabContent li,
                   7852: ul.LC_TabContentBigger li {
1.911     bisitz   7853:   float:left;
1.741     harmsja  7854: }
1.795     www      7855: 
1.897     wenzelju 7856: ul#LC_secondary_menu li a {
1.911     bisitz   7857:   color: $fontmenu;
                   7858:   text-decoration: none;
1.693     droeschl 7859: }
1.795     www      7860: 
1.721     harmsja  7861: ul.LC_TabContent {
1.952     onken    7862:   min-height:20px;
1.721     harmsja  7863: }
1.795     www      7864: 
                   7865: ul.LC_TabContent li {
1.911     bisitz   7866:   vertical-align:middle;
1.959     onken    7867:   padding: 0 16px 0 10px;
1.911     bisitz   7868:   background-color:$tabbg;
                   7869:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7870:   border-left: solid 1px $font;
1.721     harmsja  7871: }
1.795     www      7872: 
1.847     tempelho 7873: ul.LC_TabContent .right {
1.911     bisitz   7874:   float:right;
1.847     tempelho 7875: }
                   7876: 
1.911     bisitz   7877: ul.LC_TabContent li a,
                   7878: ul.LC_TabContent li {
                   7879:   color:rgb(47,47,47);
                   7880:   text-decoration:none;
                   7881:   font-size:95%;
                   7882:   font-weight:bold;
1.952     onken    7883:   min-height:20px;
                   7884: }
                   7885: 
1.959     onken    7886: ul.LC_TabContent li a:hover,
                   7887: ul.LC_TabContent li a:focus {
1.952     onken    7888:   color: $button_hover;
1.959     onken    7889:   background:none;
                   7890:   outline:none;
1.952     onken    7891: }
                   7892: 
                   7893: ul.LC_TabContent li:hover {
                   7894:   color: $button_hover;
                   7895:   cursor:pointer;
1.721     harmsja  7896: }
1.795     www      7897: 
1.911     bisitz   7898: ul.LC_TabContent li.active {
1.952     onken    7899:   color: $font;
1.911     bisitz   7900:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7901:   border-bottom:solid 1px #FFFFFF;
                   7902:   cursor: default;
1.744     ehlerst  7903: }
1.795     www      7904: 
1.959     onken    7905: ul.LC_TabContent li.active a {
                   7906:   color:$font;
                   7907:   background:#FFFFFF;
                   7908:   outline: none;
                   7909: }
1.1047    raeburn  7910: 
                   7911: ul.LC_TabContent li.goback {
                   7912:   float: left;
                   7913:   border-left: none;
                   7914: }
                   7915: 
1.870     tempelho 7916: #maincoursedoc {
1.911     bisitz   7917:   clear:both;
1.870     tempelho 7918: }
                   7919: 
                   7920: ul.LC_TabContentBigger {
1.911     bisitz   7921:   display:block;
                   7922:   list-style:none;
                   7923:   padding: 0;
1.870     tempelho 7924: }
                   7925: 
1.795     www      7926: ul.LC_TabContentBigger li {
1.911     bisitz   7927:   vertical-align:bottom;
                   7928:   height: 30px;
                   7929:   font-size:110%;
                   7930:   font-weight:bold;
                   7931:   color: #737373;
1.841     tempelho 7932: }
                   7933: 
1.957     onken    7934: ul.LC_TabContentBigger li.active {
                   7935:   position: relative;
                   7936:   top: 1px;
                   7937: }
                   7938: 
1.870     tempelho 7939: ul.LC_TabContentBigger li a {
1.911     bisitz   7940:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7941:   height: 30px;
                   7942:   line-height: 30px;
                   7943:   text-align: center;
                   7944:   display: block;
                   7945:   text-decoration: none;
1.958     onken    7946:   outline: none;  
1.741     harmsja  7947: }
1.795     www      7948: 
1.870     tempelho 7949: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7950:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7951:   color:$font;
1.744     ehlerst  7952: }
1.795     www      7953: 
1.870     tempelho 7954: ul.LC_TabContentBigger li b {
1.911     bisitz   7955:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7956:   display: block;
                   7957:   float: left;
                   7958:   padding: 0 30px;
1.957     onken    7959:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7960: }
                   7961: 
1.956     onken    7962: ul.LC_TabContentBigger li:hover b {
                   7963:   color:$button_hover;
                   7964: }
                   7965: 
1.870     tempelho 7966: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7967:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7968:   color:$font;
1.957     onken    7969:   border: 0;
1.741     harmsja  7970: }
1.693     droeschl 7971: 
1.870     tempelho 7972: 
1.862     bisitz   7973: ul.LC_CourseBreadcrumbs {
                   7974:   background: $sidebg;
1.1020    raeburn  7975:   height: 2em;
1.862     bisitz   7976:   padding-left: 10px;
1.1020    raeburn  7977:   margin: 0;
1.862     bisitz   7978:   list-style-position: inside;
                   7979: }
                   7980: 
1.911     bisitz   7981: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7982: ol#LC_PathBreadcrumbs {
1.911     bisitz   7983:   padding-left: 10px;
                   7984:   margin: 0;
1.933     droeschl 7985:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7986: }
                   7987: 
1.911     bisitz   7988: ol#LC_MenuBreadcrumbs li,
                   7989: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7990: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7991:   display: inline;
1.933     droeschl 7992:   white-space: normal;  
1.693     droeschl 7993: }
                   7994: 
1.823     bisitz   7995: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7996: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7997:   text-decoration: none;
                   7998:   font-size:90%;
1.693     droeschl 7999: }
1.795     www      8000: 
1.969     droeschl 8001: ol#LC_MenuBreadcrumbs h1 {
                   8002:   display: inline;
                   8003:   font-size: 90%;
                   8004:   line-height: 2.5em;
                   8005:   margin: 0;
                   8006:   padding: 0;
                   8007: }
                   8008: 
1.795     www      8009: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8010:   text-decoration:none;
                   8011:   font-size:100%;
                   8012:   font-weight:bold;
1.693     droeschl 8013: }
1.795     www      8014: 
1.840     bisitz   8015: .LC_Box {
1.911     bisitz   8016:   border: solid 1px $lg_border_color;
                   8017:   padding: 0 10px 10px 10px;
1.746     neumanie 8018: }
1.795     www      8019: 
1.1020    raeburn  8020: .LC_DocsBox {
                   8021:   border: solid 1px $lg_border_color;
                   8022:   padding: 0 0 10px 10px;
                   8023: }
                   8024: 
1.795     www      8025: .LC_AboutMe_Image {
1.911     bisitz   8026:   float:left;
                   8027:   margin-right:10px;
1.747     neumanie 8028: }
1.795     www      8029: 
                   8030: .LC_Clear_AboutMe_Image {
1.911     bisitz   8031:   clear:left;
1.747     neumanie 8032: }
1.795     www      8033: 
1.721     harmsja  8034: dl.LC_ListStyleClean dt {
1.911     bisitz   8035:   padding-right: 5px;
                   8036:   display: table-header-group;
1.693     droeschl 8037: }
                   8038: 
1.721     harmsja  8039: dl.LC_ListStyleClean dd {
1.911     bisitz   8040:   display: table-row;
1.693     droeschl 8041: }
                   8042: 
1.721     harmsja  8043: .LC_ListStyleClean,
                   8044: .LC_ListStyleSimple,
                   8045: .LC_ListStyleNormal,
1.795     www      8046: .LC_ListStyleSpecial {
1.911     bisitz   8047:   /* display:block; */
                   8048:   list-style-position: inside;
                   8049:   list-style-type: none;
                   8050:   overflow: hidden;
                   8051:   padding: 0;
1.693     droeschl 8052: }
                   8053: 
1.721     harmsja  8054: .LC_ListStyleSimple li,
                   8055: .LC_ListStyleSimple dd,
                   8056: .LC_ListStyleNormal li,
                   8057: .LC_ListStyleNormal dd,
                   8058: .LC_ListStyleSpecial li,
1.795     www      8059: .LC_ListStyleSpecial dd {
1.911     bisitz   8060:   margin: 0;
                   8061:   padding: 5px 5px 5px 10px;
                   8062:   clear: both;
1.693     droeschl 8063: }
                   8064: 
1.721     harmsja  8065: .LC_ListStyleClean li,
                   8066: .LC_ListStyleClean dd {
1.911     bisitz   8067:   padding-top: 0;
                   8068:   padding-bottom: 0;
1.693     droeschl 8069: }
                   8070: 
1.721     harmsja  8071: .LC_ListStyleSimple dd,
1.795     www      8072: .LC_ListStyleSimple li {
1.911     bisitz   8073:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8074: }
                   8075: 
1.721     harmsja  8076: .LC_ListStyleSpecial li,
                   8077: .LC_ListStyleSpecial dd {
1.911     bisitz   8078:   list-style-type: none;
                   8079:   background-color: RGB(220, 220, 220);
                   8080:   margin-bottom: 4px;
1.693     droeschl 8081: }
                   8082: 
1.721     harmsja  8083: table.LC_SimpleTable {
1.911     bisitz   8084:   margin:5px;
                   8085:   border:solid 1px $lg_border_color;
1.795     www      8086: }
1.693     droeschl 8087: 
1.721     harmsja  8088: table.LC_SimpleTable tr {
1.911     bisitz   8089:   padding: 0;
                   8090:   border:solid 1px $lg_border_color;
1.693     droeschl 8091: }
1.795     www      8092: 
                   8093: table.LC_SimpleTable thead {
1.911     bisitz   8094:   background:rgb(220,220,220);
1.693     droeschl 8095: }
                   8096: 
1.721     harmsja  8097: div.LC_columnSection {
1.911     bisitz   8098:   display: block;
                   8099:   clear: both;
                   8100:   overflow: hidden;
                   8101:   margin: 0;
1.693     droeschl 8102: }
                   8103: 
1.721     harmsja  8104: div.LC_columnSection>* {
1.911     bisitz   8105:   float: left;
                   8106:   margin: 10px 20px 10px 0;
                   8107:   overflow:hidden;
1.693     droeschl 8108: }
1.721     harmsja  8109: 
1.795     www      8110: table em {
1.911     bisitz   8111:   font-weight: bold;
                   8112:   font-style: normal;
1.748     schulted 8113: }
1.795     www      8114: 
1.779     bisitz   8115: table.LC_tableBrowseRes,
1.795     www      8116: table.LC_tableOfContent {
1.911     bisitz   8117:   border:none;
                   8118:   border-spacing: 1px;
                   8119:   padding: 3px;
                   8120:   background-color: #FFFFFF;
                   8121:   font-size: 90%;
1.753     droeschl 8122: }
1.789     droeschl 8123: 
1.911     bisitz   8124: table.LC_tableOfContent {
                   8125:   border-collapse: collapse;
1.789     droeschl 8126: }
                   8127: 
1.771     droeschl 8128: table.LC_tableBrowseRes a,
1.768     schulted 8129: table.LC_tableOfContent a {
1.911     bisitz   8130:   background-color: transparent;
                   8131:   text-decoration: none;
1.753     droeschl 8132: }
                   8133: 
1.795     www      8134: table.LC_tableOfContent img {
1.911     bisitz   8135:   border: none;
                   8136:   height: 1.3em;
                   8137:   vertical-align: text-bottom;
                   8138:   margin-right: 0.3em;
1.753     droeschl 8139: }
1.757     schulted 8140: 
1.795     www      8141: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8142:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8143: }
                   8144: 
1.795     www      8145: a#LC_content_toolbar_everything {
1.911     bisitz   8146:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8147: }
                   8148: 
1.795     www      8149: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8150:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8151: }
                   8152: 
1.795     www      8153: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8154:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8155: }
                   8156: 
1.795     www      8157: a#LC_content_toolbar_changefolder {
1.911     bisitz   8158:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8159: }
                   8160: 
1.795     www      8161: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8162:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8163: }
                   8164: 
1.1043    raeburn  8165: a#LC_content_toolbar_edittoplevel {
                   8166:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8167: }
                   8168: 
1.795     www      8169: ul#LC_toolbar li a:hover {
1.911     bisitz   8170:   background-position: bottom center;
1.757     schulted 8171: }
                   8172: 
1.795     www      8173: ul#LC_toolbar {
1.911     bisitz   8174:   padding: 0;
                   8175:   margin: 2px;
                   8176:   list-style:none;
                   8177:   position:relative;
                   8178:   background-color:white;
1.1082    raeburn  8179:   overflow: auto;
1.757     schulted 8180: }
                   8181: 
1.795     www      8182: ul#LC_toolbar li {
1.911     bisitz   8183:   border:1px solid white;
                   8184:   padding: 0;
                   8185:   margin: 0;
                   8186:   float: left;
                   8187:   display:inline;
                   8188:   vertical-align:middle;
1.1082    raeburn  8189:   white-space: nowrap;
1.911     bisitz   8190: }
1.757     schulted 8191: 
1.783     amueller 8192: 
1.795     www      8193: a.LC_toolbarItem {
1.911     bisitz   8194:   display:block;
                   8195:   padding: 0;
                   8196:   margin: 0;
                   8197:   height: 32px;
                   8198:   width: 32px;
                   8199:   color:white;
                   8200:   border: none;
                   8201:   background-repeat:no-repeat;
                   8202:   background-color:transparent;
1.757     schulted 8203: }
                   8204: 
1.915     droeschl 8205: ul.LC_funclist {
                   8206:     margin: 0;
                   8207:     padding: 0.5em 1em 0.5em 0;
                   8208: }
                   8209: 
1.933     droeschl 8210: ul.LC_funclist > li:first-child {
                   8211:     font-weight:bold; 
                   8212:     margin-left:0.8em;
                   8213: }
                   8214: 
1.915     droeschl 8215: ul.LC_funclist + ul.LC_funclist {
                   8216:     /* 
                   8217:        left border as a seperator if we have more than
                   8218:        one list 
                   8219:     */
                   8220:     border-left: 1px solid $sidebg;
                   8221:     /* 
                   8222:        this hides the left border behind the border of the 
                   8223:        outer box if element is wrapped to the next 'line' 
                   8224:     */
                   8225:     margin-left: -1px;
                   8226: }
                   8227: 
1.843     bisitz   8228: ul.LC_funclist li {
1.915     droeschl 8229:   display: inline;
1.782     bisitz   8230:   white-space: nowrap;
1.915     droeschl 8231:   margin: 0 0 0 25px;
                   8232:   line-height: 150%;
1.782     bisitz   8233: }
                   8234: 
1.974     wenzelju 8235: .LC_hidden {
                   8236:   display: none;
                   8237: }
                   8238: 
1.1030    www      8239: .LCmodal-overlay {
                   8240: 		position:fixed;
                   8241: 		top:0;
                   8242: 		right:0;
                   8243: 		bottom:0;
                   8244: 		left:0;
                   8245: 		height:100%;
                   8246: 		width:100%;
                   8247: 		margin:0;
                   8248: 		padding:0;
                   8249: 		background:#999;
                   8250: 		opacity:.75;
                   8251: 		filter: alpha(opacity=75);
                   8252: 		-moz-opacity: 0.75;
                   8253: 		z-index:101;
                   8254: }
                   8255: 
                   8256: * html .LCmodal-overlay {   
                   8257: 		position: absolute;
                   8258: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8259: }
                   8260: 
                   8261: .LCmodal-window {
                   8262: 		position:fixed;
                   8263: 		top:50%;
                   8264: 		left:50%;
                   8265: 		margin:0;
                   8266: 		padding:0;
                   8267: 		z-index:102;
                   8268: 	}
                   8269: 
                   8270: * html .LCmodal-window {
                   8271: 		position:absolute;
                   8272: }
                   8273: 
                   8274: .LCclose-window {
                   8275: 		position:absolute;
                   8276: 		width:32px;
                   8277: 		height:32px;
                   8278: 		right:8px;
                   8279: 		top:8px;
                   8280: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8281: 		text-indent:-99999px;
                   8282: 		overflow:hidden;
                   8283: 		cursor:pointer;
                   8284: }
                   8285: 
1.1335    raeburn  8286: pre.LC_wordwrap {
                   8287:   white-space: pre-wrap;
                   8288:   white-space: -moz-pre-wrap;
                   8289:   white-space: -pre-wrap;
                   8290:   white-space: -o-pre-wrap;
                   8291:   word-wrap: break-word;
                   8292: }
                   8293: 
1.1100    raeburn  8294: /*
1.1231    damieng  8295:   styles used for response display
                   8296: */
                   8297: div.LC_radiofoil, div.LC_rankfoil {
                   8298:   margin: .5em 0em .5em 0em;
                   8299: }
                   8300: table.LC_itemgroup {
                   8301:   margin-top: 1em;
                   8302: }
                   8303: 
                   8304: /*
1.1100    raeburn  8305:   styles used by TTH when "Default set of options to pass to tth/m
                   8306:   when converting TeX" in course settings has been set
                   8307: 
                   8308:   option passed: -t
                   8309: 
                   8310: */
                   8311: 
                   8312: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8313: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8314: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8315: td div.norm {line-height:normal;}
                   8316: 
                   8317: /*
                   8318:   option passed -y3
                   8319: */
                   8320: 
                   8321: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8322: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8323: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8324: 
1.1230    damieng  8325: /*
                   8326:   sections with roles, for content only
                   8327: */
                   8328: section[class^="role-"] {
                   8329:   padding-left: 10px;
                   8330:   padding-right: 5px;
                   8331:   margin-top: 8px;
                   8332:   margin-bottom: 8px;
                   8333:   border: 1px solid #2A4;
                   8334:   border-radius: 5px;
                   8335:   box-shadow: 0px 1px 1px #BBB;
                   8336: }
                   8337: section[class^="role-"]>h1 {
                   8338:   position: relative;
                   8339:   margin: 0px;
                   8340:   padding-top: 10px;
                   8341:   padding-left: 40px;
                   8342: }
                   8343: section[class^="role-"]>h1:before {
                   8344:   position: absolute;
                   8345:   left: -5px;
                   8346:   top: 5px;
                   8347: }
                   8348: section.role-activity>h1:before {
                   8349:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8350: }
                   8351: section.role-advice>h1:before {
                   8352:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8353: }
                   8354: section.role-bibliography>h1:before {
                   8355:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8356: }
                   8357: section.role-citation>h1:before {
                   8358:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8359: }
                   8360: section.role-conclusion>h1:before {
                   8361:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8362: }
                   8363: section.role-definition>h1:before {
                   8364:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8365: }
                   8366: section.role-demonstration>h1:before {
                   8367:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8368: }
                   8369: section.role-example>h1:before {
                   8370:   content:url('/adm/daxe/images/section_icons/example.png');
                   8371: }
                   8372: section.role-explanation>h1:before {
                   8373:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8374: }
                   8375: section.role-introduction>h1:before {
                   8376:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8377: }
                   8378: section.role-method>h1:before {
                   8379:   content:url('/adm/daxe/images/section_icons/method.png');
                   8380: }
                   8381: section.role-more_information>h1:before {
                   8382:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8383: }
                   8384: section.role-objectives>h1:before {
                   8385:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8386: }
                   8387: section.role-prerequisites>h1:before {
                   8388:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8389: }
                   8390: section.role-remark>h1:before {
                   8391:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8392: }
                   8393: section.role-reminder>h1:before {
                   8394:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8395: }
                   8396: section.role-summary>h1:before {
                   8397:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8398: }
                   8399: section.role-syntax>h1:before {
                   8400:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8401: }
                   8402: section.role-warning>h1:before {
                   8403:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8404: }
                   8405: 
1.1269    raeburn  8406: #LC_minitab_header {
                   8407:   float:left;
                   8408:   width:100%;
                   8409:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8410:   font-size:93%;
                   8411:   line-height:normal;
                   8412:   margin: 0.5em 0 0.5em 0;
                   8413: }
                   8414: #LC_minitab_header ul {
                   8415:   margin:0;
                   8416:   padding:10px 10px 0;
                   8417:   list-style:none;
                   8418: }
                   8419: #LC_minitab_header li {
                   8420:   float:left;
                   8421:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8422:   margin:0;
                   8423:   padding:0 0 0 9px;
                   8424: }
                   8425: #LC_minitab_header a {
                   8426:   display:block;
                   8427:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8428:   padding:5px 15px 4px 6px;
                   8429: }
                   8430: #LC_minitab_header #LC_current_minitab {
                   8431:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8432: }
                   8433: #LC_minitab_header #LC_current_minitab a {
                   8434:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8435:   padding-bottom:5px;
                   8436: }
                   8437: 
                   8438: 
1.343     albertel 8439: END
                   8440: }
                   8441: 
1.306     albertel 8442: =pod
                   8443: 
                   8444: =item * &headtag()
                   8445: 
                   8446: Returns a uniform footer for LON-CAPA web pages.
                   8447: 
1.307     albertel 8448: Inputs: $title - optional title for the head
                   8449:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8450:         $args - optional arguments
1.319     albertel 8451:             force_register - if is true call registerurl so the remote is 
                   8452:                              informed
1.415     albertel 8453:             redirect       -> array ref of
                   8454:                                    1- seconds before redirect occurs
                   8455:                                    2- url to redirect to
                   8456:                                    3- whether the side effect should occur
1.315     albertel 8457:                            (side effect of setting 
                   8458:                                $env{'internal.head.redirect'} to the url 
                   8459:                                redirected too)
1.352     albertel 8460:             domain         -> force to color decorate a page for a specific
                   8461:                                domain
                   8462:             function       -> force usage of a specific rolish color scheme
                   8463:             bgcolor        -> override the default page bgcolor
1.460     albertel 8464:             no_auto_mt_title
                   8465:                            -> prevent &mt()ing the title arg
1.464     albertel 8466: 
1.306     albertel 8467: =cut
                   8468: 
                   8469: sub headtag {
1.313     albertel 8470:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8471:     
1.363     albertel 8472:     my $function = $args->{'function'} || &get_users_function();
                   8473:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8474:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8475:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8476:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8477: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8478: 		   #time(),
1.418     albertel 8479: 		   $env{'environment.color.timestamp'},
1.363     albertel 8480: 		   $function,$domain,$bgcolor);
                   8481: 
1.369     www      8482:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8483: 
1.308     albertel 8484:     my $result =
                   8485: 	'<head>'.
1.1160    raeburn  8486: 	&font_settings($args);
1.319     albertel 8487: 
1.1188    raeburn  8488:     my $inhibitprint;
                   8489:     if ($args->{'print_suppress'}) {
                   8490:         $inhibitprint = &print_suppression();
                   8491:     }
1.1064    raeburn  8492: 
1.461     albertel 8493:     if (!$args->{'frameset'}) {
                   8494: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8495:     }
1.962     droeschl 8496:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8497:         $result .= Apache::lonxml::display_title();
1.319     albertel 8498:     }
1.436     albertel 8499:     if (!$args->{'no_nav_bar'} 
                   8500: 	&& !$args->{'only_body'}
                   8501: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8502: 	$result .= &help_menu_js($httphost);
1.1032    www      8503:         $result.=&modal_window();
1.1038    www      8504:         $result.=&togglebox_script();
1.1034    www      8505:         $result.=&wishlist_window();
1.1041    www      8506:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8507:     } else {
                   8508:         if ($args->{'add_modal'}) {
                   8509:            $result.=&modal_window();
                   8510:         }
                   8511:         if ($args->{'add_wishlist'}) {
                   8512:            $result.=&wishlist_window();
                   8513:         }
1.1038    www      8514:         if ($args->{'add_togglebox'}) {
                   8515:            $result.=&togglebox_script();
                   8516:         }
1.1041    www      8517:         if ($args->{'add_progressbar'}) {
                   8518:            $result.=&LCprogressbarUpdate_script();
                   8519:         }
1.436     albertel 8520:     }
1.314     albertel 8521:     if (ref($args->{'redirect'})) {
1.414     albertel 8522: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8523: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8524: 	if (!$inhibit_continue) {
                   8525: 	    $env{'internal.head.redirect'} = $url;
                   8526: 	}
1.313     albertel 8527: 	$result.=<<ADDMETA
                   8528: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8529: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8530: ADDMETA
1.1210    raeburn  8531:     } else {
                   8532:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8533:             my $requrl = $env{'request.uri'};
                   8534:             if ($requrl eq '') {
                   8535:                 $requrl = $ENV{'REQUEST_URI'};
                   8536:                 $requrl =~ s/\?.+$//;
                   8537:             }
                   8538:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8539:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8540:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8541:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8542:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8543:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8544:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8545:                     my $offload;
1.1210    raeburn  8546:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8547:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8548:                             $offload = 1;
                   8549:                         }
                   8550:                     }
                   8551:                     unless ($offload) {
                   8552:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8553:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8554:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8555:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8556:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8557:                                         $offload = 1;
                   8558:                                         $dom_in_use = $env{'user.domain'};
                   8559:                                     }
1.1210    raeburn  8560:                                 }
1.1340    raeburn  8561:                             }
                   8562:                         }
                   8563:                     }
                   8564:                     if ($offload) {
                   8565:                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8566:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8567:                             my $numsec = 5;
                   8568:                             my $timeout = $numsec * 1000;
                   8569:                             my ($newurl,$locknum,%locks,$msg);
                   8570:                             if ($env{'request.role.adv'}) {
                   8571:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8572:                             }
                   8573:                             my $disable_submit = 0;
                   8574:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8575:                                 $disable_submit = 1;
                   8576:                             }
                   8577:                             if ($locknum) {
                   8578:                                 my @lockinfo = sort(values(%locks));
                   8579:                                 $msg = &mt('Once the following tasks are complete: ')."\n".
                   8580:                                        join(", ",sort(values(%locks)))."\n";
                   8581:                                 if (&show_course()) {
                   8582:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8583:                                 } else {
                   8584:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8585:                                 }
1.1340    raeburn  8586:                             } else {
                   8587:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8588:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8589:                                 }
                   8590:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8591:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8592:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8593:                                     $newurl .= '&role='.$env{'request.role'};
                   8594:                                 }
                   8595:                                 if ($env{'request.symb'}) {
                   8596:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8597:                                     if ($shownsymb =~ m{^/enc/}) {
                   8598:                                         my $reqdmajor = 2;
                   8599:                                         my $reqdminor = 11;
                   8600:                                         my $reqdsubminor = 3;
                   8601:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8602:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8603:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8604:                                         if (($major eq '' && $minor eq '') ||
                   8605:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8606:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8607:                                              ($reqdsubminor > $subminor))))) {
                   8608:                                             undef($shownsymb);
                   8609:                                         }
1.1210    raeburn  8610:                                     }
1.1340    raeburn  8611:                                     if ($shownsymb) {
                   8612:                                         &js_escape(\$shownsymb);
                   8613:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  8614:                                     }
1.1340    raeburn  8615:                                 } else {
                   8616:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8617:                                     &js_escape(\$shownurl);
                   8618:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  8619:                                 }
1.1340    raeburn  8620:                             }
                   8621:                             &js_escape(\$msg);
                   8622:                             $result.=<<OFFLOAD
1.1210    raeburn  8623: <meta http-equiv="pragma" content="no-cache" />
                   8624: <script type="text/javascript">
1.1215    raeburn  8625: // <![CDATA[
1.1210    raeburn  8626: function LC_Offload_Now() {
                   8627:     var dest = "$newurl";
                   8628:     if (dest != '') {
                   8629:         window.location.href="$newurl";
                   8630:     }
                   8631: }
1.1214    raeburn  8632: \$(document).ready(function () {
                   8633:     window.alert('$msg');
                   8634:     if ($disable_submit) {
1.1210    raeburn  8635:         \$(".LC_hwk_submit").prop("disabled", true);
                   8636:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8637:     }
                   8638:     setTimeout('LC_Offload_Now()', $timeout);
                   8639: });
1.1215    raeburn  8640: // ]]>
1.1210    raeburn  8641: </script>
                   8642: OFFLOAD
                   8643:                         }
                   8644:                     }
                   8645:                 }
                   8646:             }
                   8647:         }
1.313     albertel 8648:     }
1.306     albertel 8649:     if (!defined($title)) {
                   8650: 	$title = 'The LearningOnline Network with CAPA';
                   8651:     }
1.460     albertel 8652:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8653:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8654: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8655:     if (!$args->{'frameset'}) {
                   8656:         $result .= ' /';
                   8657:     }
                   8658:     $result .= '>' 
1.1064    raeburn  8659:         .$inhibitprint
1.414     albertel 8660: 	.$head_extra;
1.1242    raeburn  8661:     my $clientmobile;
                   8662:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8663:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8664:     } else {
                   8665:         $clientmobile = $env{'browser.mobile'};
                   8666:     }
                   8667:     if ($clientmobile) {
1.1137    raeburn  8668:         $result .= '
                   8669: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8670: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8671:     }
1.1278    raeburn  8672:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8673:     return $result.'</head>';
1.306     albertel 8674: }
                   8675: 
                   8676: =pod
                   8677: 
1.340     albertel 8678: =item * &font_settings()
                   8679: 
                   8680: Returns neccessary <meta> to set the proper encoding
                   8681: 
1.1160    raeburn  8682: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8683: 
                   8684: =cut
                   8685: 
                   8686: sub font_settings {
1.1160    raeburn  8687:     my ($args) = @_;
1.340     albertel 8688:     my $headerstring='';
1.1160    raeburn  8689:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8690:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8691:         $headerstring.=
                   8692:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8693:         if (!$args->{'frameset'}) {
                   8694: 	    $headerstring.= ' /';
                   8695:         }
                   8696: 	$headerstring .= '>'."\n";
1.340     albertel 8697:     }
                   8698:     return $headerstring;
                   8699: }
                   8700: 
1.341     albertel 8701: =pod
                   8702: 
1.1064    raeburn  8703: =item * &print_suppression()
                   8704: 
                   8705: In course context returns css which causes the body to be blank when media="print",
                   8706: if printout generation is unavailable for the current resource.
                   8707: 
                   8708: This could be because:
                   8709: 
                   8710: (a) printstartdate is in the future
                   8711: 
                   8712: (b) printenddate is in the past
                   8713: 
                   8714: (c) there is an active exam block with "printout"
                   8715: functionality blocked
                   8716: 
                   8717: Users with pav, pfo or evb privileges are exempt.
                   8718: 
                   8719: Inputs: none
                   8720: 
                   8721: =cut
                   8722: 
                   8723: 
                   8724: sub print_suppression {
                   8725:     my $noprint;
                   8726:     if ($env{'request.course.id'}) {
                   8727:         my $scope = $env{'request.course.id'};
                   8728:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8729:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8730:             return;
                   8731:         }
                   8732:         if ($env{'request.course.sec'} ne '') {
                   8733:             $scope .= "/$env{'request.course.sec'}";
                   8734:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8735:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8736:                 return;
1.1064    raeburn  8737:             }
                   8738:         }
                   8739:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8740:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8741:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8742:         if ($blocked) {
                   8743:             my $checkrole = "cm./$cdom/$cnum";
                   8744:             if ($env{'request.course.sec'} ne '') {
                   8745:                 $checkrole .= "/$env{'request.course.sec'}";
                   8746:             }
                   8747:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8748:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8749:                 $noprint = 1;
                   8750:             }
                   8751:         }
                   8752:         unless ($noprint) {
                   8753:             my $symb = &Apache::lonnet::symbread();
                   8754:             if ($symb ne '') {
                   8755:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8756:                 if (ref($navmap)) {
                   8757:                     my $res = $navmap->getBySymb($symb);
                   8758:                     if (ref($res)) {
                   8759:                         if (!$res->resprintable()) {
                   8760:                             $noprint = 1;
                   8761:                         }
                   8762:                     }
                   8763:                 }
                   8764:             }
                   8765:         }
                   8766:         if ($noprint) {
                   8767:             return <<"ENDSTYLE";
                   8768: <style type="text/css" media="print">
                   8769:     body { display:none }
                   8770: </style>
                   8771: ENDSTYLE
                   8772:         }
                   8773:     }
                   8774:     return;
                   8775: }
                   8776: 
                   8777: =pod
                   8778: 
1.341     albertel 8779: =item * &xml_begin()
                   8780: 
                   8781: Returns the needed doctype and <html>
                   8782: 
                   8783: Inputs: none
                   8784: 
                   8785: =cut
                   8786: 
                   8787: sub xml_begin {
1.1168    raeburn  8788:     my ($is_frameset) = @_;
1.341     albertel 8789:     my $output='';
                   8790: 
                   8791:     if ($env{'browser.mathml'}) {
                   8792: 	$output='<?xml version="1.0"?>'
                   8793:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8794: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8795:             
                   8796: #	    .'<!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">] >'
                   8797: 	    .'<!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">'
                   8798:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8799: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8800:     } elsif ($is_frameset) {
                   8801:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8802:                 '<html>'."\n";
1.341     albertel 8803:     } else {
1.1168    raeburn  8804: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8805:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8806:     }
                   8807:     return $output;
                   8808: }
1.340     albertel 8809: 
                   8810: =pod
                   8811: 
1.306     albertel 8812: =item * &start_page()
                   8813: 
                   8814: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8815: 
1.648     raeburn  8816: Inputs:
                   8817: 
                   8818: =over 4
                   8819: 
                   8820: $title - optional title for the page
                   8821: 
                   8822: $head_extra - optional extra HTML to incude inside the <head>
                   8823: 
                   8824: $args - additional optional args supported are:
                   8825: 
                   8826: =over 8
                   8827: 
                   8828:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8829:                                     arg on
1.814     bisitz   8830:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8831:              add_entries    -> additional attributes to add to the  <body>
                   8832:              domain         -> force to color decorate a page for a 
1.317     albertel 8833:                                     specific domain
1.648     raeburn  8834:              function       -> force usage of a specific rolish color
1.317     albertel 8835:                                     scheme
1.648     raeburn  8836:              redirect       -> see &headtag()
                   8837:              bgcolor        -> override the default page bg color
                   8838:              js_ready       -> return a string ready for being used in 
1.317     albertel 8839:                                     a javascript writeln
1.648     raeburn  8840:              html_encode    -> return a string ready for being used in 
1.320     albertel 8841:                                     a html attribute
1.648     raeburn  8842:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8843:                                     $forcereg arg
1.648     raeburn  8844:              frameset       -> if true will start with a <frameset>
1.330     albertel 8845:                                     rather than <body>
1.648     raeburn  8846:              skip_phases    -> hash ref of 
1.338     albertel 8847:                                     head -> skip the <html><head> generation
                   8848:                                     body -> skip all <body> generation
1.648     raeburn  8849:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8850:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8851:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8852:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8853:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8854:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8855:                                specific group
                   8856:              use_absolute   -> for request for external resource or syllabus, this
                   8857:                                will contain https://<hostname> if server uses
                   8858:                                https (as per hosts.tab), but request is for http
                   8859:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8860: 
1.648     raeburn  8861: =back
1.460     albertel 8862: 
1.648     raeburn  8863: =back
1.562     albertel 8864: 
1.306     albertel 8865: =cut
                   8866: 
                   8867: sub start_page {
1.309     albertel 8868:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8869:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8870: 
1.315     albertel 8871:     $env{'internal.start_page'}++;
1.1318    raeburn  8872:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu);
1.964     droeschl 8873: 
1.338     albertel 8874:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8875:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8876:     }
1.1316    raeburn  8877: 
                   8878:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  8879:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8880:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8881:                 $args->{'no_primary_menu'} = 1;
                   8882:             }
                   8883:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8884:                 $args->{'no_inline_menu'} = 1;
                   8885:             }
                   8886:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8887:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8888:             }
                   8889:         } else {
                   8890:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8891:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8892:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8893:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8894:                     $args->{'no_primary_menu'} = 1;
                   8895:                 }
                   8896:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8897:                     $args->{'no_inline_menu'} = 1;
                   8898:                 }
                   8899:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8900:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8901:                 }
                   8902:             }
                   8903:         }
1.1316    raeburn  8904:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8905:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8906:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8907:     }
1.338     albertel 8908:     
                   8909:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8910: 	if ($args->{'frameset'}) {
                   8911: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8912: 						$args->{'add_entries'});
                   8913: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8914:         } else {
                   8915:             $result .=
                   8916:                 &bodytag($title, 
                   8917:                          $args->{'function'},       $args->{'add_entries'},
                   8918:                          $args->{'only_body'},      $args->{'domain'},
                   8919:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8920:                          $args->{'bgcolor'},        $args,
1.1318    raeburn  8921:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu);
1.831     bisitz   8922:         }
1.330     albertel 8923:     }
1.338     albertel 8924: 
1.315     albertel 8925:     if ($args->{'js_ready'}) {
1.713     kaisler  8926: 		$result = &js_ready($result);
1.315     albertel 8927:     }
1.320     albertel 8928:     if ($args->{'html_encode'}) {
1.713     kaisler  8929: 		$result = &html_encode($result);
                   8930:     }
                   8931: 
1.813     bisitz   8932:     # Preparation for new and consistent functionlist at top of screen
                   8933:     # if ($args->{'functionlist'}) {
                   8934:     #            $result .= &build_functionlist();
                   8935:     #}
                   8936: 
1.964     droeschl 8937:     # Don't add anything more if only_body wanted or in const space
                   8938:     return $result if    $args->{'only_body'} 
                   8939:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8940: 
                   8941:     #Breadcrumbs
1.758     kaisler  8942:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8943: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8944: 		#if any br links exists, add them to the breadcrumbs
                   8945: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8946: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8947: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8948: 			}
                   8949: 		}
1.1096    raeburn  8950:                 # if @advtools array contains items add then to the breadcrumbs
                   8951:                 if (@advtools > 0) {
                   8952:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8953:                 }
1.1272    raeburn  8954:                 my $menulink;
                   8955:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8956:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  8957:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  8958:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8959:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8960:                      (!$env{'request.role.adv'}))) {
                   8961:                     $menulink = 0;
                   8962:                 } else {
                   8963:                     undef($menulink);
                   8964:                 }
1.758     kaisler  8965: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8966: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8967: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8968:                 } else {
1.1272    raeburn  8969: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8970: 		}
1.320     albertel 8971:     }
1.315     albertel 8972:     return $result;
1.306     albertel 8973: }
                   8974: 
                   8975: sub end_page {
1.315     albertel 8976:     my ($args) = @_;
                   8977:     $env{'internal.end_page'}++;
1.330     albertel 8978:     my $result;
1.335     albertel 8979:     if ($args->{'discussion'}) {
                   8980: 	my ($target,$parser);
                   8981: 	if (ref($args->{'discussion'})) {
                   8982: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8983: 				$args->{'discussion'}{'parser'});
                   8984: 	}
                   8985: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8986:     }
1.330     albertel 8987:     if ($args->{'frameset'}) {
                   8988: 	$result .= '</frameset>';
                   8989:     } else {
1.635     raeburn  8990: 	$result .= &endbodytag($args);
1.330     albertel 8991:     }
1.1080    raeburn  8992:     unless ($args->{'notbody'}) {
                   8993:         $result .= "\n</html>";
                   8994:     }
1.330     albertel 8995: 
1.315     albertel 8996:     if ($args->{'js_ready'}) {
1.317     albertel 8997: 	$result = &js_ready($result);
1.315     albertel 8998:     }
1.335     albertel 8999: 
1.320     albertel 9000:     if ($args->{'html_encode'}) {
                   9001: 	$result = &html_encode($result);
                   9002:     }
1.335     albertel 9003: 
1.315     albertel 9004:     return $result;
                   9005: }
                   9006: 
1.1034    www      9007: sub wishlist_window {
                   9008:     return(<<'ENDWISHLIST');
1.1046    raeburn  9009: <script type="text/javascript">
1.1034    www      9010: // <![CDATA[
                   9011: // <!-- BEGIN LON-CAPA Internal
                   9012: function set_wishlistlink(title, path) {
                   9013:     if (!title) {
                   9014:         title = document.title;
                   9015:         title = title.replace(/^LON-CAPA /,'');
                   9016:     }
1.1175    raeburn  9017:     title = encodeURIComponent(title);
1.1203    raeburn  9018:     title = title.replace("'","\\\'");
1.1034    www      9019:     if (!path) {
                   9020:         path = location.pathname;
                   9021:     }
1.1175    raeburn  9022:     path = encodeURIComponent(path);
1.1203    raeburn  9023:     path = path.replace("'","\\\'");
1.1034    www      9024:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9025:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9026: }
                   9027: // END LON-CAPA Internal -->
                   9028: // ]]>
                   9029: </script>
                   9030: ENDWISHLIST
                   9031: }
                   9032: 
1.1030    www      9033: sub modal_window {
                   9034:     return(<<'ENDMODAL');
1.1046    raeburn  9035: <script type="text/javascript">
1.1030    www      9036: // <![CDATA[
                   9037: // <!-- BEGIN LON-CAPA Internal
                   9038: var modalWindow = {
                   9039: 	parent:"body",
                   9040: 	windowId:null,
                   9041: 	content:null,
                   9042: 	width:null,
                   9043: 	height:null,
                   9044: 	close:function()
                   9045: 	{
                   9046: 	        $(".LCmodal-window").remove();
                   9047: 	        $(".LCmodal-overlay").remove();
                   9048: 	},
                   9049: 	open:function()
                   9050: 	{
                   9051: 		var modal = "";
                   9052: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9053: 		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;\">";
                   9054: 		modal += this.content;
                   9055: 		modal += "</div>";	
                   9056: 
                   9057: 		$(this.parent).append(modal);
                   9058: 
                   9059: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9060: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9061: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9062: 	}
                   9063: };
1.1140    raeburn  9064: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9065: 	{
1.1266    raeburn  9066:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9067: 		modalWindow.windowId = "myModal";
                   9068: 		modalWindow.width = width;
                   9069: 		modalWindow.height = height;
1.1196    raeburn  9070: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9071: 		modalWindow.open();
1.1208    raeburn  9072: 	};
1.1030    www      9073: // END LON-CAPA Internal -->
                   9074: // ]]>
                   9075: </script>
                   9076: ENDMODAL
                   9077: }
                   9078: 
                   9079: sub modal_link {
1.1140    raeburn  9080:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9081:     unless ($width) { $width=480; }
                   9082:     unless ($height) { $height=400; }
1.1031    www      9083:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9084:     unless ($transparency) { $transparency='true'; }
                   9085: 
1.1074    raeburn  9086:     my $target_attr;
                   9087:     if (defined($target)) {
                   9088:         $target_attr = 'target="'.$target.'"';
                   9089:     }
                   9090:     return <<"ENDLINK";
1.1336    raeburn  9091: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9092: ENDLINK
1.1030    www      9093: }
                   9094: 
1.1032    www      9095: sub modal_adhoc_script {
                   9096:     my ($funcname,$width,$height,$content)=@_;
                   9097:     return (<<ENDADHOC);
1.1046    raeburn  9098: <script type="text/javascript">
1.1032    www      9099: // <![CDATA[
                   9100:         var $funcname = function()
                   9101:         {
                   9102:                 modalWindow.windowId = "myModal";
                   9103:                 modalWindow.width = $width;
                   9104:                 modalWindow.height = $height;
                   9105:                 modalWindow.content = '$content';
                   9106:                 modalWindow.open();
                   9107:         };  
                   9108: // ]]>
                   9109: </script>
                   9110: ENDADHOC
                   9111: }
                   9112: 
1.1041    www      9113: sub modal_adhoc_inner {
                   9114:     my ($funcname,$width,$height,$content)=@_;
                   9115:     my $innerwidth=$width-20;
                   9116:     $content=&js_ready(
1.1140    raeburn  9117:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9118:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9119:                  $content.
1.1041    www      9120:                  &end_scrollbox().
1.1140    raeburn  9121:                  &end_page()
1.1041    www      9122:              );
                   9123:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   9124: }
                   9125: 
                   9126: sub modal_adhoc_window {
                   9127:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   9128:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   9129:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9130: }
                   9131: 
                   9132: sub modal_adhoc_launch {
                   9133:     my ($funcname,$width,$height,$content)=@_;
                   9134:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9135: <script type="text/javascript">
                   9136: // <![CDATA[
                   9137: $funcname();
                   9138: // ]]>
                   9139: </script>
                   9140: ENDLAUNCH
                   9141: }
                   9142: 
                   9143: sub modal_adhoc_close {
                   9144:     return (<<ENDCLOSE);
                   9145: <script type="text/javascript">
                   9146: // <![CDATA[
                   9147: modalWindow.close();
                   9148: // ]]>
                   9149: </script>
                   9150: ENDCLOSE
                   9151: }
                   9152: 
1.1038    www      9153: sub togglebox_script {
                   9154:    return(<<ENDTOGGLE);
                   9155: <script type="text/javascript"> 
                   9156: // <![CDATA[
                   9157: function LCtoggleDisplay(id,hidetext,showtext) {
                   9158:    link = document.getElementById(id + "link").childNodes[0];
                   9159:    with (document.getElementById(id).style) {
                   9160:       if (display == "none" ) {
                   9161:           display = "inline";
                   9162:           link.nodeValue = hidetext;
                   9163:         } else {
                   9164:           display = "none";
                   9165:           link.nodeValue = showtext;
                   9166:        }
                   9167:    }
                   9168: }
                   9169: // ]]>
                   9170: </script>
                   9171: ENDTOGGLE
                   9172: }
                   9173: 
1.1039    www      9174: sub start_togglebox {
                   9175:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9176:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9177:     unless ($showtext) { $showtext=&mt('show'); }
                   9178:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9179:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9180:     return &start_data_table().
                   9181:            &start_data_table_header_row().
                   9182:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9183:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9184:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9185:            &end_data_table_header_row().
                   9186:            '<tr id="'.$id.'" style="display:none""><td>';
                   9187: }
                   9188: 
                   9189: sub end_togglebox {
                   9190:     return '</td></tr>'.&end_data_table();
                   9191: }
                   9192: 
1.1041    www      9193: sub LCprogressbar_script {
1.1302    raeburn  9194:    my ($id,$number_to_do)=@_;
                   9195:    if ($number_to_do) {
                   9196:        return(<<ENDPROGRESS);
1.1041    www      9197: <script type="text/javascript">
                   9198: // <![CDATA[
1.1045    www      9199: \$('#progressbar$id').progressbar({
1.1041    www      9200:   value: 0,
                   9201:   change: function(event, ui) {
                   9202:     var newVal = \$(this).progressbar('option', 'value');
                   9203:     \$('.pblabel', this).text(LCprogressTxt);
                   9204:   }
                   9205: });
                   9206: // ]]>
                   9207: </script>
                   9208: ENDPROGRESS
1.1302    raeburn  9209:    } else {
                   9210:        return(<<ENDPROGRESS);
                   9211: <script type="text/javascript">
                   9212: // <![CDATA[
                   9213: \$('#progressbar$id').progressbar({
                   9214:   value: false,
                   9215:   create: function(event, ui) {
                   9216:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9217:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9218:   }
                   9219: });
                   9220: // ]]>
                   9221: </script>
                   9222: ENDPROGRESS
                   9223:    }
1.1041    www      9224: }
                   9225: 
                   9226: sub LCprogressbarUpdate_script {
                   9227:    return(<<ENDPROGRESSUPDATE);
                   9228: <style type="text/css">
                   9229: .ui-progressbar { position:relative; }
1.1302    raeburn  9230: .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      9231: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9232: </style>
                   9233: <script type="text/javascript">
                   9234: // <![CDATA[
1.1045    www      9235: var LCprogressTxt='---';
                   9236: 
1.1302    raeburn  9237: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9238:    LCprogressTxt=progresstext;
1.1302    raeburn  9239:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9240:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9241:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9242:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9243:    } else {
                   9244:        \$('#progressbar'+id).progressbar('value',percent);
                   9245:    }
1.1041    www      9246: }
                   9247: // ]]>
                   9248: </script>
                   9249: ENDPROGRESSUPDATE
                   9250: }
                   9251: 
1.1042    www      9252: my $LClastpercent;
1.1045    www      9253: my $LCidcnt;
                   9254: my $LCcurrentid;
1.1042    www      9255: 
1.1041    www      9256: sub LCprogressbar {
1.1302    raeburn  9257:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9258:     $LClastpercent=0;
1.1045    www      9259:     $LCidcnt++;
                   9260:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9261:     my ($starting,$content);
                   9262:     if ($number_to_do) {
                   9263:         $starting=&mt('Starting');
                   9264:         $content=(<<ENDPROGBAR);
                   9265: $preamble
1.1045    www      9266:   <div id="progressbar$LCcurrentid">
1.1041    www      9267:     <span class="pblabel">$starting</span>
                   9268:   </div>
                   9269: ENDPROGBAR
1.1302    raeburn  9270:     } else {
                   9271:         $starting=&mt('Loading...');
                   9272:         $LClastpercent='false';
                   9273:         $content=(<<ENDPROGBAR);
                   9274: $preamble
                   9275:   <div id="progressbar$LCcurrentid">
                   9276:       <div class="progress-label">$starting</div>
                   9277:   </div>
                   9278: ENDPROGBAR
                   9279:     }
                   9280:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9281: }
                   9282: 
                   9283: sub LCprogressbarUpdate {
1.1302    raeburn  9284:     my ($r,$val,$text,$number_to_do)=@_;
                   9285:     if ($number_to_do) {
                   9286:         unless ($val) { 
                   9287:             if ($LClastpercent) {
                   9288:                 $val=$LClastpercent;
                   9289:             } else {
                   9290:                 $val=0;
                   9291:             }
                   9292:         }
                   9293:         if ($val<0) { $val=0; }
                   9294:         if ($val>100) { $val=0; }
                   9295:         $LClastpercent=$val;
                   9296:         unless ($text) { $text=$val.'%'; }
                   9297:     } else {
                   9298:         $val = 'false';
1.1042    www      9299:     }
1.1041    www      9300:     $text=&js_ready($text);
1.1044    www      9301:     &r_print($r,<<ENDUPDATE);
1.1041    www      9302: <script type="text/javascript">
                   9303: // <![CDATA[
1.1302    raeburn  9304: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9305: // ]]>
                   9306: </script>
                   9307: ENDUPDATE
1.1035    www      9308: }
                   9309: 
1.1042    www      9310: sub LCprogressbarClose {
                   9311:     my ($r)=@_;
                   9312:     $LClastpercent=0;
1.1044    www      9313:     &r_print($r,<<ENDCLOSE);
1.1042    www      9314: <script type="text/javascript">
                   9315: // <![CDATA[
1.1045    www      9316: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9317: // ]]>
                   9318: </script>
                   9319: ENDCLOSE
1.1044    www      9320: }
                   9321: 
                   9322: sub r_print {
                   9323:     my ($r,$to_print)=@_;
                   9324:     if ($r) {
                   9325:       $r->print($to_print);
                   9326:       $r->rflush();
                   9327:     } else {
                   9328:       print($to_print);
                   9329:     }
1.1042    www      9330: }
                   9331: 
1.320     albertel 9332: sub html_encode {
                   9333:     my ($result) = @_;
                   9334: 
1.322     albertel 9335:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9336:     
                   9337:     return $result;
                   9338: }
1.1044    www      9339: 
1.317     albertel 9340: sub js_ready {
                   9341:     my ($result) = @_;
                   9342: 
1.323     albertel 9343:     $result =~ s/[\n\r]/ /xmsg;
                   9344:     $result =~ s/\\/\\\\/xmsg;
                   9345:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9346:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9347:     
                   9348:     return $result;
                   9349: }
                   9350: 
1.315     albertel 9351: sub validate_page {
                   9352:     if (  exists($env{'internal.start_page'})
1.316     albertel 9353: 	  &&     $env{'internal.start_page'} > 1) {
                   9354: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9355: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9356: 				 $ENV{'request.filename'});
1.315     albertel 9357:     }
                   9358:     if (  exists($env{'internal.end_page'})
1.316     albertel 9359: 	  &&     $env{'internal.end_page'} > 1) {
                   9360: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9361: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9362: 				 $env{'request.filename'});
1.315     albertel 9363:     }
                   9364:     if (     exists($env{'internal.start_page'})
                   9365: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9366: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9367: 				 $env{'request.filename'});
1.315     albertel 9368:     }
                   9369:     if (   ! exists($env{'internal.start_page'})
                   9370: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9371: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9372: 				 $env{'request.filename'});
1.315     albertel 9373:     }
1.306     albertel 9374: }
1.315     albertel 9375: 
1.996     www      9376: 
                   9377: sub start_scrollbox {
1.1140    raeburn  9378:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9379:     unless ($outerwidth) { $outerwidth='520px'; }
                   9380:     unless ($width) { $width='500px'; }
                   9381:     unless ($height) { $height='200px'; }
1.1075    raeburn  9382:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9383:     if ($id ne '') {
1.1140    raeburn  9384:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9385:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9386:     }
1.1075    raeburn  9387:     if ($bgcolor ne '') {
                   9388:         $tdcol = "background-color: $bgcolor;";
                   9389:     }
1.1137    raeburn  9390:     my $nicescroll_js;
                   9391:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9392:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9393:     }
                   9394:     return <<"END";
                   9395: $nicescroll_js
                   9396: 
                   9397: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9398: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9399: END
                   9400: }
                   9401: 
                   9402: sub end_scrollbox {
                   9403:     return '</div></td></tr></table>';
                   9404: }
                   9405: 
                   9406: sub nicescroll_javascript {
                   9407:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9408:     my %options;
                   9409:     if (ref($cursor) eq 'HASH') {
                   9410:         %options = %{$cursor};
                   9411:     }
                   9412:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9413:         $options{'railalign'} = 'left';
                   9414:     }
                   9415:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9416:         my $function  = &get_users_function();
                   9417:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9418:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9419:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9420:         }
1.1140    raeburn  9421:     }
                   9422:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9423:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9424:             $options{'cursoropacity'}='1.0';
                   9425:         }
1.1140    raeburn  9426:     } else {
                   9427:         $options{'cursoropacity'}='1.0';
                   9428:     }
                   9429:     if ($options{'cursorfixedheight'} eq 'none') {
                   9430:         delete($options{'cursorfixedheight'});
                   9431:     } else {
                   9432:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9433:     }
                   9434:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9435:         delete($options{'railoffset'});
                   9436:     }
                   9437:     my @niceoptions;
                   9438:     while (my($key,$value) = each(%options)) {
                   9439:         if ($value =~ /^\{.+\}$/) {
                   9440:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9441:         } else {
1.1140    raeburn  9442:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9443:         }
1.1140    raeburn  9444:     }
                   9445:     my $nicescroll_js = '
1.1137    raeburn  9446: $(document).ready(
1.1140    raeburn  9447:       function() {
                   9448:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9449:       }
1.1137    raeburn  9450: );
                   9451: ';
1.1140    raeburn  9452:     if ($framecheck) {
                   9453:         $nicescroll_js .= '
                   9454: function expand_div(caller) {
                   9455:     if (top === self) {
                   9456:         document.getElementById("'.$id.'").style.width = "auto";
                   9457:         document.getElementById("'.$id.'").style.height = "auto";
                   9458:     } else {
                   9459:         try {
                   9460:             if (parent.frames) {
                   9461:                 if (parent.frames.length > 1) {
                   9462:                     var framesrc = parent.frames[1].location.href;
                   9463:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9464:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9465:                         document.getElementById("'.$id.'").style.width = "auto";
                   9466:                         document.getElementById("'.$id.'").style.height = "auto";
                   9467:                     }
                   9468:                 }
                   9469:             }
                   9470:         } catch (e) {
                   9471:             return;
                   9472:         }
1.1137    raeburn  9473:     }
1.1140    raeburn  9474:     return;
1.996     www      9475: }
1.1140    raeburn  9476: ';
                   9477:     }
                   9478:     if ($needjsready) {
                   9479:         $nicescroll_js = '
                   9480: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9481:     } else {
                   9482:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9483:     }
                   9484:     return $nicescroll_js;
1.996     www      9485: }
                   9486: 
1.318     albertel 9487: sub simple_error_page {
1.1150    bisitz   9488:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9489:     my %displayargs;
1.1151    raeburn  9490:     if (ref($args) eq 'HASH') {
                   9491:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9492:         if ($args->{'only_body'}) {
                   9493:             $displayargs{'only_body'} = 1;
                   9494:         }
                   9495:         if ($args->{'no_nav_bar'}) {
                   9496:             $displayargs{'no_nav_bar'} = 1;
                   9497:         }
1.1151    raeburn  9498:     } else {
                   9499:         $msg = &mt($msg);
                   9500:     }
1.1150    bisitz   9501: 
1.318     albertel 9502:     my $page =
1.1304    raeburn  9503: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9504: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9505: 	&Apache::loncommon::end_page();
                   9506:     if (ref($r)) {
                   9507: 	$r->print($page);
1.327     albertel 9508: 	return;
1.318     albertel 9509:     }
                   9510:     return $page;
                   9511: }
1.347     albertel 9512: 
                   9513: {
1.610     albertel 9514:     my @row_count;
1.961     onken    9515: 
                   9516:     sub start_data_table_count {
                   9517:         unshift(@row_count, 0);
                   9518:         return;
                   9519:     }
                   9520: 
                   9521:     sub end_data_table_count {
                   9522:         shift(@row_count);
                   9523:         return;
                   9524:     }
                   9525: 
1.347     albertel 9526:     sub start_data_table {
1.1018    raeburn  9527: 	my ($add_class,$id) = @_;
1.422     albertel 9528: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9529:         my $table_id;
                   9530:         if (defined($id)) {
                   9531:             $table_id = ' id="'.$id.'"';
                   9532:         }
1.961     onken    9533: 	&start_data_table_count();
1.1018    raeburn  9534: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9535:     }
                   9536: 
                   9537:     sub end_data_table {
1.961     onken    9538: 	&end_data_table_count();
1.389     albertel 9539: 	return '</table>'."\n";;
1.347     albertel 9540:     }
                   9541: 
                   9542:     sub start_data_table_row {
1.974     wenzelju 9543: 	my ($add_class, $id) = @_;
1.610     albertel 9544: 	$row_count[0]++;
                   9545: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9546: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9547:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9548:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9549:     }
1.471     banghart 9550:     
                   9551:     sub continue_data_table_row {
1.974     wenzelju 9552: 	my ($add_class, $id) = @_;
1.610     albertel 9553: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9554: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9555:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9556:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9557:     }
1.347     albertel 9558: 
                   9559:     sub end_data_table_row {
1.389     albertel 9560: 	return '</tr>'."\n";;
1.347     albertel 9561:     }
1.367     www      9562: 
1.421     albertel 9563:     sub start_data_table_empty_row {
1.707     bisitz   9564: #	$row_count[0]++;
1.421     albertel 9565: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9566:     }
                   9567: 
                   9568:     sub end_data_table_empty_row {
                   9569: 	return '</tr>'."\n";;
                   9570:     }
                   9571: 
1.367     www      9572:     sub start_data_table_header_row {
1.389     albertel 9573: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9574:     }
                   9575: 
                   9576:     sub end_data_table_header_row {
1.389     albertel 9577: 	return '</tr>'."\n";;
1.367     www      9578:     }
1.890     droeschl 9579: 
                   9580:     sub data_table_caption {
                   9581:         my $caption = shift;
                   9582:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9583:     }
1.347     albertel 9584: }
                   9585: 
1.548     albertel 9586: =pod
                   9587: 
                   9588: =item * &inhibit_menu_check($arg)
                   9589: 
                   9590: Checks for a inhibitmenu state and generates output to preserve it
                   9591: 
                   9592: Inputs:         $arg - can be any of
                   9593:                      - undef - in which case the return value is a string 
                   9594:                                to add  into arguments list of a uri
                   9595:                      - 'input' - in which case the return value is a HTML
                   9596:                                  <form> <input> field of type hidden to
                   9597:                                  preserve the value
                   9598:                      - a url - in which case the return value is the url with
                   9599:                                the neccesary cgi args added to preserve the
                   9600:                                inhibitmenu state
                   9601:                      - a ref to a url - no return value, but the string is
                   9602:                                         updated to include the neccessary cgi
                   9603:                                         args to preserve the inhibitmenu state
                   9604: 
                   9605: =cut
                   9606: 
                   9607: sub inhibit_menu_check {
                   9608:     my ($arg) = @_;
                   9609:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9610:     if ($arg eq 'input') {
                   9611: 	if ($env{'form.inhibitmenu'}) {
                   9612: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9613: 	} else {
                   9614: 	    return
                   9615: 	}
                   9616:     }
                   9617:     if ($env{'form.inhibitmenu'}) {
                   9618: 	if (ref($arg)) {
                   9619: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9620: 	} elsif ($arg eq '') {
                   9621: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9622: 	} else {
                   9623: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9624: 	}
                   9625:     }
                   9626:     if (!ref($arg)) {
                   9627: 	return $arg;
                   9628:     }
                   9629: }
                   9630: 
1.251     albertel 9631: ###############################################
1.182     matthew  9632: 
                   9633: =pod
                   9634: 
1.549     albertel 9635: =back
                   9636: 
                   9637: =head1 User Information Routines
                   9638: 
                   9639: =over 4
                   9640: 
1.405     albertel 9641: =item * &get_users_function()
1.182     matthew  9642: 
                   9643: Used by &bodytag to determine the current users primary role.
                   9644: Returns either 'student','coordinator','admin', or 'author'.
                   9645: 
                   9646: =cut
                   9647: 
                   9648: ###############################################
                   9649: sub get_users_function {
1.815     tempelho 9650:     my $function = 'norole';
1.818     tempelho 9651:     if ($env{'request.role'}=~/^(st)/) {
                   9652:         $function='student';
                   9653:     }
1.907     raeburn  9654:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9655:         $function='coordinator';
                   9656:     }
1.258     albertel 9657:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9658:         $function='admin';
                   9659:     }
1.826     bisitz   9660:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9661:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9662:         $function='author';
                   9663:     }
                   9664:     return $function;
1.54      www      9665: }
1.99      www      9666: 
                   9667: ###############################################
                   9668: 
1.233     raeburn  9669: =pod
                   9670: 
1.821     raeburn  9671: =item * &show_course()
                   9672: 
                   9673: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9674: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9675: 
                   9676: Inputs:
                   9677: None
                   9678: 
                   9679: Outputs:
                   9680: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9681: 
                   9682: =cut
                   9683: 
                   9684: ###############################################
                   9685: sub show_course {
                   9686:     my $course = !$env{'user.adv'};
                   9687:     if (!$env{'user.adv'}) {
                   9688:         foreach my $env (keys(%env)) {
                   9689:             next if ($env !~ m/^user\.priv\./);
                   9690:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9691:                 $course = 0;
                   9692:                 last;
                   9693:             }
                   9694:         }
                   9695:     }
                   9696:     return $course;
                   9697: }
                   9698: 
                   9699: ###############################################
                   9700: 
                   9701: =pod
                   9702: 
1.542     raeburn  9703: =item * &check_user_status()
1.274     raeburn  9704: 
                   9705: Determines current status of supplied role for a
                   9706: specific user. Roles can be active, previous or future.
                   9707: 
                   9708: Inputs: 
                   9709: user's domain, user's username, course's domain,
1.375     raeburn  9710: course's number, optional section ID.
1.274     raeburn  9711: 
                   9712: Outputs:
                   9713: role status: active, previous or future. 
                   9714: 
                   9715: =cut
                   9716: 
                   9717: sub check_user_status {
1.412     raeburn  9718:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9719:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9720:     my @uroles = keys(%userinfo);
1.274     raeburn  9721:     my $srchstr;
                   9722:     my $active_chk = 'none';
1.412     raeburn  9723:     my $now = time;
1.274     raeburn  9724:     if (@uroles > 0) {
1.908     raeburn  9725:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9726:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9727:         } else {
1.412     raeburn  9728:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9729:         }
                   9730:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9731:             my $role_end = 0;
                   9732:             my $role_start = 0;
                   9733:             $active_chk = 'active';
1.412     raeburn  9734:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9735:                 $role_end = $1;
                   9736:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9737:                     $role_start = $1;
1.274     raeburn  9738:                 }
                   9739:             }
                   9740:             if ($role_start > 0) {
1.412     raeburn  9741:                 if ($now < $role_start) {
1.274     raeburn  9742:                     $active_chk = 'future';
                   9743:                 }
                   9744:             }
                   9745:             if ($role_end > 0) {
1.412     raeburn  9746:                 if ($now > $role_end) {
1.274     raeburn  9747:                     $active_chk = 'previous';
                   9748:                 }
                   9749:             }
                   9750:         }
                   9751:     }
                   9752:     return $active_chk;
                   9753: }
                   9754: 
                   9755: ###############################################
                   9756: 
                   9757: =pod
                   9758: 
1.405     albertel 9759: =item * &get_sections()
1.233     raeburn  9760: 
                   9761: Determines all the sections for a course including
                   9762: sections with students and sections containing other roles.
1.419     raeburn  9763: Incoming parameters: 
                   9764: 
                   9765: 1. domain
                   9766: 2. course number 
                   9767: 3. reference to array containing roles for which sections should 
                   9768: be gathered (optional).
                   9769: 4. reference to array containing status types for which sections 
                   9770: should be gathered (optional).
                   9771: 
                   9772: If the third argument is undefined, sections are gathered for any role. 
                   9773: If the fourth argument is undefined, sections are gathered for any status.
                   9774: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9775:  
1.374     raeburn  9776: Returns section hash (keys are section IDs, values are
                   9777: number of users in each section), subject to the
1.419     raeburn  9778: optional roles filter, optional status filter 
1.233     raeburn  9779: 
                   9780: =cut
                   9781: 
                   9782: ###############################################
                   9783: sub get_sections {
1.419     raeburn  9784:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9785:     if (!defined($cdom) || !defined($cnum)) {
                   9786:         my $cid =  $env{'request.course.id'};
                   9787: 
                   9788: 	return if (!defined($cid));
                   9789: 
                   9790:         $cdom = $env{'course.'.$cid.'.domain'};
                   9791:         $cnum = $env{'course.'.$cid.'.num'};
                   9792:     }
                   9793: 
                   9794:     my %sectioncount;
1.419     raeburn  9795:     my $now = time;
1.240     albertel 9796: 
1.1118    raeburn  9797:     my $check_students = 1;
                   9798:     my $only_students = 0;
                   9799:     if (ref($possible_roles) eq 'ARRAY') {
                   9800:         if (grep(/^st$/,@{$possible_roles})) {
                   9801:             if (@{$possible_roles} == 1) {
                   9802:                 $only_students = 1;
                   9803:             }
                   9804:         } else {
                   9805:             $check_students = 0;
                   9806:         }
                   9807:     }
                   9808: 
                   9809:     if ($check_students) { 
1.276     albertel 9810: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9811: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9812: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9813:         my $start_index = &Apache::loncoursedata::CL_START();
                   9814:         my $end_index = &Apache::loncoursedata::CL_END();
                   9815:         my $status;
1.366     albertel 9816: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9817: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9818: 				                     $data->[$status_index],
                   9819:                                                      $data->[$start_index],
                   9820:                                                      $data->[$end_index]);
                   9821:             if ($stu_status eq 'Active') {
                   9822:                 $status = 'active';
                   9823:             } elsif ($end < $now) {
                   9824:                 $status = 'previous';
                   9825:             } elsif ($start > $now) {
                   9826:                 $status = 'future';
                   9827:             } 
                   9828: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9829:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9830:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9831: 		    $sectioncount{$section}++;
                   9832:                 }
1.240     albertel 9833: 	    }
                   9834: 	}
                   9835:     }
1.1118    raeburn  9836:     if ($only_students) {
                   9837:         return %sectioncount;
                   9838:     }
1.240     albertel 9839:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9840:     foreach my $user (sort(keys(%courseroles))) {
                   9841: 	if ($user !~ /^(\w{2})/) { next; }
                   9842: 	my ($role) = ($user =~ /^(\w{2})/);
                   9843: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9844: 	my ($section,$status);
1.240     albertel 9845: 	if ($role eq 'cr' &&
                   9846: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9847: 	    $section=$1;
                   9848: 	}
                   9849: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9850: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9851:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9852:         if ($end == -1 && $start == -1) {
                   9853:             next; #deleted role
                   9854:         }
                   9855:         if (!defined($possible_status)) { 
                   9856:             $sectioncount{$section}++;
                   9857:         } else {
                   9858:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9859:                 $status = 'active';
                   9860:             } elsif ($end < $now) {
                   9861:                 $status = 'future';
                   9862:             } elsif ($start > $now) {
                   9863:                 $status = 'previous';
                   9864:             }
                   9865:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9866:                 $sectioncount{$section}++;
                   9867:             }
                   9868:         }
1.233     raeburn  9869:     }
1.366     albertel 9870:     return %sectioncount;
1.233     raeburn  9871: }
                   9872: 
1.274     raeburn  9873: ###############################################
1.294     raeburn  9874: 
                   9875: =pod
1.405     albertel 9876: 
                   9877: =item * &get_course_users()
                   9878: 
1.275     raeburn  9879: Retrieves usernames:domains for users in the specified course
                   9880: with specific role(s), and access status. 
                   9881: 
                   9882: Incoming parameters:
1.277     albertel 9883: 1. course domain
                   9884: 2. course number
                   9885: 3. access status: users must have - either active, 
1.275     raeburn  9886: previous, future, or all.
1.277     albertel 9887: 4. reference to array of permissible roles
1.288     raeburn  9888: 5. reference to array of section restrictions (optional)
                   9889: 6. reference to results object (hash of hashes).
                   9890: 7. reference to optional userdata hash
1.609     raeburn  9891: 8. reference to optional statushash
1.630     raeburn  9892: 9. flag if privileged users (except those set to unhide in
                   9893:    course settings) should be excluded    
1.609     raeburn  9894: Keys of top level results hash are roles.
1.275     raeburn  9895: Keys of inner hashes are username:domain, with 
                   9896: values set to access type.
1.288     raeburn  9897: Optional userdata hash returns an array with arguments in the 
                   9898: same order as loncoursedata::get_classlist() for student data.
                   9899: 
1.609     raeburn  9900: Optional statushash returns
                   9901: 
1.288     raeburn  9902: Entries for end, start, section and status are blank because
                   9903: of the possibility of multiple values for non-student roles.
                   9904: 
1.275     raeburn  9905: =cut
1.405     albertel 9906: 
1.275     raeburn  9907: ###############################################
1.405     albertel 9908: 
1.275     raeburn  9909: sub get_course_users {
1.630     raeburn  9910:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9911:     my %idx = ();
1.419     raeburn  9912:     my %seclists;
1.288     raeburn  9913: 
                   9914:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9915:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9916:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9917:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9918:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9919:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9920:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9921:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9922: 
1.290     albertel 9923:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9924:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9925:         my $now = time;
1.277     albertel 9926:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9927:             my $match = 0;
1.412     raeburn  9928:             my $secmatch = 0;
1.419     raeburn  9929:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9930:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9931:             if ($section eq '') {
                   9932:                 $section = 'none';
                   9933:             }
1.291     albertel 9934:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9935:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9936:                     $secmatch = 1;
                   9937:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9938:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9939:                         $secmatch = 1;
                   9940:                     }
                   9941:                 } else {  
1.419     raeburn  9942: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9943: 		        $secmatch = 1;
                   9944:                     }
1.290     albertel 9945: 		}
1.412     raeburn  9946:                 if (!$secmatch) {
                   9947:                     next;
                   9948:                 }
1.419     raeburn  9949:             }
1.275     raeburn  9950:             if (defined($$types{'active'})) {
1.288     raeburn  9951:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9952:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9953:                     $match = 1;
1.275     raeburn  9954:                 }
                   9955:             }
                   9956:             if (defined($$types{'previous'})) {
1.609     raeburn  9957:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9958:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9959:                     $match = 1;
1.275     raeburn  9960:                 }
                   9961:             }
                   9962:             if (defined($$types{'future'})) {
1.609     raeburn  9963:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9964:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9965:                     $match = 1;
1.275     raeburn  9966:                 }
                   9967:             }
1.609     raeburn  9968:             if ($match) {
                   9969:                 push(@{$seclists{$student}},$section);
                   9970:                 if (ref($userdata) eq 'HASH') {
                   9971:                     $$userdata{$student} = $$classlist{$student};
                   9972:                 }
                   9973:                 if (ref($statushash) eq 'HASH') {
                   9974:                     $statushash->{$student}{'st'}{$section} = $status;
                   9975:                 }
1.288     raeburn  9976:             }
1.275     raeburn  9977:         }
                   9978:     }
1.412     raeburn  9979:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9980:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9981:         my $now = time;
1.609     raeburn  9982:         my %displaystatus = ( previous => 'Expired',
                   9983:                               active   => 'Active',
                   9984:                               future   => 'Future',
                   9985:                             );
1.1121    raeburn  9986:         my (%nothide,@possdoms);
1.630     raeburn  9987:         if ($hidepriv) {
                   9988:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9989:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9990:                 if ($user !~ /:/) {
                   9991:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9992:                 } else {
                   9993:                     $nothide{$user} = 1;
                   9994:                 }
                   9995:             }
1.1121    raeburn  9996:             my @possdoms = ($cdom);
                   9997:             if ($coursehash{'checkforpriv'}) {
                   9998:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9999:             }
1.630     raeburn  10000:         }
1.439     raeburn  10001:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10002:             my $match = 0;
1.412     raeburn  10003:             my $secmatch = 0;
1.439     raeburn  10004:             my $status;
1.412     raeburn  10005:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10006:             $user =~ s/:$//;
1.439     raeburn  10007:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10008:             if ($end == -1 || $start == -1) {
                   10009:                 next;
                   10010:             }
                   10011:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10012:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10013:                 my ($uname,$udom) = split(/:/,$user);
                   10014:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10015:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10016:                         $secmatch = 1;
                   10017:                     } elsif ($usec eq '') {
1.420     albertel 10018:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10019:                             $secmatch = 1;
                   10020:                         }
                   10021:                     } else {
                   10022:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10023:                             $secmatch = 1;
                   10024:                         }
                   10025:                     }
                   10026:                     if (!$secmatch) {
                   10027:                         next;
                   10028:                     }
1.288     raeburn  10029:                 }
1.419     raeburn  10030:                 if ($usec eq '') {
                   10031:                     $usec = 'none';
                   10032:                 }
1.275     raeburn  10033:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10034:                     if ($hidepriv) {
1.1121    raeburn  10035:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10036:                             (!$nothide{$uname.':'.$udom})) {
                   10037:                             next;
                   10038:                         }
                   10039:                     }
1.503     raeburn  10040:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10041:                         $status = 'previous';
                   10042:                     } elsif ($start > $now) {
                   10043:                         $status = 'future';
                   10044:                     } else {
                   10045:                         $status = 'active';
                   10046:                     }
1.277     albertel 10047:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10048:                         if ($status eq $type) {
1.420     albertel 10049:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10050:                                 push(@{$$users{$role}{$user}},$type);
                   10051:                             }
1.288     raeburn  10052:                             $match = 1;
                   10053:                         }
                   10054:                     }
1.419     raeburn  10055:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10056:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10057: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10058:                         }
1.420     albertel 10059:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10060:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10061:                         }
1.609     raeburn  10062:                         if (ref($statushash) eq 'HASH') {
                   10063:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10064:                         }
1.275     raeburn  10065:                     }
                   10066:                 }
                   10067:             }
                   10068:         }
1.290     albertel 10069:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10070:             if ((defined($cdom)) && (defined($cnum))) {
                   10071:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10072:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10073:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10074:                     next if ($owner eq '');
                   10075:                     my ($ownername,$ownerdom);
                   10076:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10077:                         $ownername = $1;
                   10078:                         $ownerdom = $2;
                   10079:                     } else {
                   10080:                         $ownername = $owner;
                   10081:                         $ownerdom = $cdom;
                   10082:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10083:                     }
                   10084:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10085:                     if (defined($userdata) && 
1.609     raeburn  10086: 			!exists($$userdata{$owner})) {
                   10087: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10088:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10089:                             push(@{$seclists{$owner}},'none');
                   10090:                         }
                   10091:                         if (ref($statushash) eq 'HASH') {
                   10092:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10093:                         }
1.290     albertel 10094: 		    }
1.279     raeburn  10095:                 }
                   10096:             }
                   10097:         }
1.419     raeburn  10098:         foreach my $user (keys(%seclists)) {
                   10099:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10100:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10101:         }
1.275     raeburn  10102:     }
                   10103:     return;
                   10104: }
                   10105: 
1.288     raeburn  10106: sub get_user_info {
                   10107:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10108:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10109: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10110:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10111:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10112:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10113:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10114:     return;
                   10115: }
1.275     raeburn  10116: 
1.472     raeburn  10117: ###############################################
                   10118: 
                   10119: =pod
                   10120: 
                   10121: =item * &get_user_quota()
                   10122: 
1.1134    raeburn  10123: Retrieves quota assigned for storage of user files.
                   10124: Default is to report quota for portfolio files.
1.472     raeburn  10125: 
                   10126: Incoming parameters:
                   10127: 1. user's username
                   10128: 2. user's domain
1.1134    raeburn  10129: 3. quota name - portfolio, author, or course
1.1136    raeburn  10130:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10131: 4. crstype - official, unofficial, textbook, placement or community, 
                   10132:    if quota name is course
1.472     raeburn  10133: 
                   10134: Returns:
1.1163    raeburn  10135: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10136: 2. (Optional) Type of setting: custom or default
                   10137:    (individually assigned or default for user's 
                   10138:    institutional status).
                   10139: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10140:    or student - types as defined in localenroll::inst_usertypes 
                   10141:    for user's domain, which determines default quota for user.
                   10142: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10143: 
                   10144: If a value has been stored in the user's environment, 
1.536     raeburn  10145: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10146: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10147: 
                   10148: =cut
                   10149: 
                   10150: ###############################################
                   10151: 
                   10152: 
                   10153: sub get_user_quota {
1.1136    raeburn  10154:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10155:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10156:     if (!defined($udom)) {
                   10157:         $udom = $env{'user.domain'};
                   10158:     }
                   10159:     if (!defined($uname)) {
                   10160:         $uname = $env{'user.name'};
                   10161:     }
                   10162:     if (($udom eq '' || $uname eq '') ||
                   10163:         ($udom eq 'public') && ($uname eq 'public')) {
                   10164:         $quota = 0;
1.536     raeburn  10165:         $quotatype = 'default';
                   10166:         $defquota = 0; 
1.472     raeburn  10167:     } else {
1.536     raeburn  10168:         my $inststatus;
1.1134    raeburn  10169:         if ($quotaname eq 'course') {
                   10170:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10171:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10172:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10173:             } else {
                   10174:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10175:                 $quota = $cenv{'internal.uploadquota'};
                   10176:             }
1.536     raeburn  10177:         } else {
1.1134    raeburn  10178:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10179:                 if ($quotaname eq 'author') {
                   10180:                     $quota = $env{'environment.authorquota'};
                   10181:                 } else {
                   10182:                     $quota = $env{'environment.portfolioquota'};
                   10183:                 }
                   10184:                 $inststatus = $env{'environment.inststatus'};
                   10185:             } else {
                   10186:                 my %userenv = 
                   10187:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10188:                                          'authorquota','inststatus'],$udom,$uname);
                   10189:                 my ($tmp) = keys(%userenv);
                   10190:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10191:                     if ($quotaname eq 'author') {
                   10192:                         $quota = $userenv{'authorquota'};
                   10193:                     } else {
                   10194:                         $quota = $userenv{'portfolioquota'};
                   10195:                     }
                   10196:                     $inststatus = $userenv{'inststatus'};
                   10197:                 } else {
                   10198:                     undef(%userenv);
                   10199:                 }
                   10200:             }
                   10201:         }
                   10202:         if ($quota eq '' || wantarray) {
                   10203:             if ($quotaname eq 'course') {
                   10204:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10205:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10206:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10207:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10208:                     $defquota = $domdefs{$crstype.'quota'};
                   10209:                 }
                   10210:                 if ($defquota eq '') {
                   10211:                     $defquota = 500;
                   10212:                 }
1.1134    raeburn  10213:             } else {
                   10214:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10215:             }
                   10216:             if ($quota eq '') {
                   10217:                 $quota = $defquota;
                   10218:                 $quotatype = 'default';
                   10219:             } else {
                   10220:                 $quotatype = 'custom';
                   10221:             }
1.472     raeburn  10222:         }
                   10223:     }
1.536     raeburn  10224:     if (wantarray) {
                   10225:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10226:     } else {
                   10227:         return $quota;
                   10228:     }
1.472     raeburn  10229: }
                   10230: 
                   10231: ###############################################
                   10232: 
                   10233: =pod
                   10234: 
                   10235: =item * &default_quota()
                   10236: 
1.536     raeburn  10237: Retrieves default quota assigned for storage of user portfolio files,
                   10238: given an (optional) user's institutional status.
1.472     raeburn  10239: 
                   10240: Incoming parameters:
1.1142    raeburn  10241: 
1.472     raeburn  10242: 1. domain
1.536     raeburn  10243: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10244:    status types (e.g., faculty, staff, student etc.)
                   10245:    which apply to the user for whom the default is being retrieved.
                   10246:    If the institutional status string in undefined, the domain
1.1134    raeburn  10247:    default quota will be returned.
                   10248: 3.  quota name - portfolio, author, or course
                   10249:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10250: 
                   10251: Returns:
1.1142    raeburn  10252: 
1.1163    raeburn  10253: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10254: 2. (Optional) institutional type which determined the value of the
                   10255:    default quota.
1.472     raeburn  10256: 
                   10257: If a value has been stored in the domain's configuration db,
                   10258: it will return that, otherwise it returns 20 (for backwards 
                   10259: compatibility with domains which have not set up a configuration
1.1163    raeburn  10260: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10261: 
1.536     raeburn  10262: If the user's status includes multiple types (e.g., staff and student),
                   10263: the largest default quota which applies to the user determines the
                   10264: default quota returned.
                   10265: 
1.472     raeburn  10266: =cut
                   10267: 
                   10268: ###############################################
                   10269: 
                   10270: 
                   10271: sub default_quota {
1.1134    raeburn  10272:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10273:     my ($defquota,$settingstatus);
                   10274:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10275:                                             ['quotas'],$udom);
1.1134    raeburn  10276:     my $key = 'defaultquota';
                   10277:     if ($quotaname eq 'author') {
                   10278:         $key = 'authorquota';
                   10279:     }
1.622     raeburn  10280:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10281:         if ($inststatus ne '') {
1.765     raeburn  10282:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10283:             foreach my $item (@statuses) {
1.1134    raeburn  10284:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10285:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10286:                         if ($defquota eq '') {
1.1134    raeburn  10287:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10288:                             $settingstatus = $item;
1.1134    raeburn  10289:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10290:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10291:                             $settingstatus = $item;
                   10292:                         }
                   10293:                     }
1.1134    raeburn  10294:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10295:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10296:                         if ($defquota eq '') {
                   10297:                             $defquota = $quotahash{'quotas'}{$item};
                   10298:                             $settingstatus = $item;
                   10299:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10300:                             $defquota = $quotahash{'quotas'}{$item};
                   10301:                             $settingstatus = $item;
                   10302:                         }
1.536     raeburn  10303:                     }
                   10304:                 }
                   10305:             }
                   10306:         }
                   10307:         if ($defquota eq '') {
1.1134    raeburn  10308:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10309:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10310:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10311:                 $defquota = $quotahash{'quotas'}{'default'};
                   10312:             }
1.536     raeburn  10313:             $settingstatus = 'default';
1.1139    raeburn  10314:             if ($defquota eq '') {
                   10315:                 if ($quotaname eq 'author') {
                   10316:                     $defquota = 500;
                   10317:                 }
                   10318:             }
1.536     raeburn  10319:         }
                   10320:     } else {
                   10321:         $settingstatus = 'default';
1.1134    raeburn  10322:         if ($quotaname eq 'author') {
                   10323:             $defquota = 500;
                   10324:         } else {
                   10325:             $defquota = 20;
                   10326:         }
1.536     raeburn  10327:     }
                   10328:     if (wantarray) {
                   10329:         return ($defquota,$settingstatus);
1.472     raeburn  10330:     } else {
1.536     raeburn  10331:         return $defquota;
1.472     raeburn  10332:     }
                   10333: }
                   10334: 
1.1135    raeburn  10335: ###############################################
                   10336: 
                   10337: =pod
                   10338: 
1.1136    raeburn  10339: =item * &excess_filesize_warning()
1.1135    raeburn  10340: 
                   10341: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10342: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10343: space to be exceeded.
1.1136    raeburn  10344: 
                   10345: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10346: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10347: 
1.1165    raeburn  10348: Inputs: 7 
1.1136    raeburn  10349: 1. username or coursenum
1.1135    raeburn  10350: 2. domain
1.1136    raeburn  10351: 3. context ('author' or 'course')
1.1135    raeburn  10352: 4. filename of file for which action is being requested
                   10353: 5. filesize (kB) of file
                   10354: 6. action being taken: copy or upload.
1.1237    raeburn  10355: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10356: 
                   10357: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10358:          otherwise return null.
                   10359: 
                   10360: =back
1.1135    raeburn  10361: 
                   10362: =cut
                   10363: 
1.1136    raeburn  10364: sub excess_filesize_warning {
1.1165    raeburn  10365:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10366:     my $current_disk_usage = 0;
1.1165    raeburn  10367:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10368:     if ($context eq 'author') {
                   10369:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10370:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10371:     } else {
                   10372:         foreach my $subdir ('docs','supplemental') {
                   10373:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10374:         }
                   10375:     }
1.1135    raeburn  10376:     $disk_quota = int($disk_quota * 1000);
                   10377:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10378:         return '<p class="LC_warning">'.
1.1135    raeburn  10379:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10380:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10381:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10382:                             $disk_quota,$current_disk_usage).
                   10383:                '</p>';
                   10384:     }
                   10385:     return;
                   10386: }
                   10387: 
                   10388: ###############################################
                   10389: 
                   10390: 
1.1136    raeburn  10391: 
                   10392: 
1.384     raeburn  10393: sub get_secgrprole_info {
                   10394:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10395:     my %sections_count = &get_sections($cdom,$cnum);
                   10396:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10397:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10398:     my @groups = sort(keys(%curr_groups));
                   10399:     my $allroles = [];
                   10400:     my $rolehash;
                   10401:     my $accesshash = {
                   10402:                      active => 'Currently has access',
                   10403:                      future => 'Will have future access',
                   10404:                      previous => 'Previously had access',
                   10405:                   };
                   10406:     if ($needroles) {
                   10407:         $rolehash = {'all' => 'all'};
1.385     albertel 10408:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10409: 	if (&Apache::lonnet::error(%user_roles)) {
                   10410: 	    undef(%user_roles);
                   10411: 	}
                   10412:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10413:             my ($role)=split(/\:/,$item,2);
                   10414:             if ($role eq 'cr') { next; }
                   10415:             if ($role =~ /^cr/) {
                   10416:                 $$rolehash{$role} = (split('/',$role))[3];
                   10417:             } else {
                   10418:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10419:             }
                   10420:         }
                   10421:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10422:             push(@{$allroles},$key);
                   10423:         }
                   10424:         push (@{$allroles},'st');
                   10425:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10426:     }
                   10427:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10428: }
                   10429: 
1.555     raeburn  10430: sub user_picker {
1.1279    raeburn  10431:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10432:     my $currdom = $dom;
1.1253    raeburn  10433:     my @alldoms = &Apache::lonnet::all_domains();
                   10434:     if (@alldoms == 1) {
                   10435:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10436:                                                ['directorysrch'],$alldoms[0]);
                   10437:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10438:         my $showdom = $domdesc;
                   10439:         if ($showdom eq '') {
                   10440:             $showdom = $dom;
                   10441:         }
                   10442:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10443:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10444:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10445:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10446:             }
                   10447:         }
                   10448:     }
1.555     raeburn  10449:     my %curr_selected = (
                   10450:                         srchin => 'dom',
1.580     raeburn  10451:                         srchby => 'lastname',
1.555     raeburn  10452:                       );
                   10453:     my $srchterm;
1.625     raeburn  10454:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10455:         if ($srch->{'srchby'} ne '') {
                   10456:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10457:         }
                   10458:         if ($srch->{'srchin'} ne '') {
                   10459:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10460:         }
                   10461:         if ($srch->{'srchtype'} ne '') {
                   10462:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10463:         }
                   10464:         if ($srch->{'srchdomain'} ne '') {
                   10465:             $currdom = $srch->{'srchdomain'};
                   10466:         }
                   10467:         $srchterm = $srch->{'srchterm'};
                   10468:     }
1.1222    damieng  10469:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10470:                     'usr'       => 'Search criteria',
1.563     raeburn  10471:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10472:                     'uname'     => 'username',
                   10473:                     'lastname'  => 'last name',
1.555     raeburn  10474:                     'lastfirst' => 'last name, first name',
1.558     albertel 10475:                     'crs'       => 'in this course',
1.576     raeburn  10476:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10477:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10478:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10479:                     'exact'     => 'is',
                   10480:                     'contains'  => 'contains',
1.569     raeburn  10481:                     'begins'    => 'begins with',
1.1222    damieng  10482:                                        );
                   10483:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10484:                     'youm'      => "You must include some text to search for.",
                   10485:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10486:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10487:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10488:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10489:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10490:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10491:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10492:                                        );
1.1222    damieng  10493:     &html_escape(\%html_lt);
                   10494:     &js_escape(\%js_lt);
1.1255    raeburn  10495:     my $domform;
1.1277    raeburn  10496:     my $allow_blank = 1;
1.1255    raeburn  10497:     if ($fixeddom) {
1.1277    raeburn  10498:         $allow_blank = 0;
                   10499:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10500:     } else {
1.1287    raeburn  10501:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10502:         my ($trusted,$untrusted);
1.1287    raeburn  10503:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10504:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10505:         } elsif ($context eq 'author') {
1.1288    raeburn  10506:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10507:         } elsif ($context eq 'domain') {
1.1288    raeburn  10508:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10509:         }
1.1288    raeburn  10510:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10511:     }
1.563     raeburn  10512:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10513: 
                   10514:     my @srchins = ('crs','dom','alc','instd');
                   10515: 
                   10516:     foreach my $option (@srchins) {
                   10517:         # FIXME 'alc' option unavailable until 
                   10518:         #       loncreateuser::print_user_query_page()
                   10519:         #       has been completed.
                   10520:         next if ($option eq 'alc');
1.880     raeburn  10521:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10522:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10523:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10524:         if ($curr_selected{'srchin'} eq $option) {
                   10525:             $srchinsel .= ' 
1.1222    damieng  10526:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10527:         } else {
                   10528:             $srchinsel .= '
1.1222    damieng  10529:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10530:         }
1.555     raeburn  10531:     }
1.563     raeburn  10532:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10533: 
                   10534:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10535:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10536:         if ($curr_selected{'srchby'} eq $option) {
                   10537:             $srchbysel .= '
1.1222    damieng  10538:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10539:         } else {
                   10540:             $srchbysel .= '
1.1222    damieng  10541:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10542:          }
                   10543:     }
                   10544:     $srchbysel .= "\n  </select>\n";
                   10545: 
                   10546:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10547:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10548:         if ($curr_selected{'srchtype'} eq $option) {
                   10549:             $srchtypesel .= '
1.1222    damieng  10550:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10551:         } else {
                   10552:             $srchtypesel .= '
1.1222    damieng  10553:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10554:         }
                   10555:     }
                   10556:     $srchtypesel .= "\n  </select>\n";
                   10557: 
1.558     albertel 10558:     my ($newuserscript,$new_user_create);
1.994     raeburn  10559:     my $context_dom = $env{'request.role.domain'};
                   10560:     if ($context eq 'requestcrs') {
                   10561:         if ($env{'form.coursedom'} ne '') { 
                   10562:             $context_dom = $env{'form.coursedom'};
                   10563:         }
                   10564:     }
1.556     raeburn  10565:     if ($forcenewuser) {
1.576     raeburn  10566:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10567:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10568:                 if ($cancreate) {
                   10569:                     $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>';
                   10570:                 } else {
1.799     bisitz   10571:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10572:                     my %usertypetext = (
                   10573:                         official   => 'institutional',
                   10574:                         unofficial => 'non-institutional',
                   10575:                     );
1.799     bisitz   10576:                     $new_user_create = '<p class="LC_warning">'
                   10577:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10578:                                       .' '
                   10579:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10580:                                           ,'<a href="'.$helplink.'">','</a>')
                   10581:                                       .'</p><br />';
1.627     raeburn  10582:                 }
1.576     raeburn  10583:             }
                   10584:         }
                   10585: 
1.556     raeburn  10586:         $newuserscript = <<"ENDSCRIPT";
                   10587: 
1.570     raeburn  10588: function setSearch(createnew,callingForm) {
1.556     raeburn  10589:     if (createnew == 1) {
1.570     raeburn  10590:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10591:             if (callingForm.srchby.options[i].value == 'uname') {
                   10592:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10593:             }
                   10594:         }
1.570     raeburn  10595:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10596:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10597: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10598:             }
                   10599:         }
1.570     raeburn  10600:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10601:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10602:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10603:             }
                   10604:         }
1.570     raeburn  10605:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10606:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10607:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10608:             }
                   10609:         }
                   10610:     }
                   10611: }
                   10612: ENDSCRIPT
1.558     albertel 10613: 
1.556     raeburn  10614:     }
                   10615: 
1.555     raeburn  10616:     my $output = <<"END_BLOCK";
1.556     raeburn  10617: <script type="text/javascript">
1.824     bisitz   10618: // <![CDATA[
1.570     raeburn  10619: function validateEntry(callingForm) {
1.558     albertel 10620: 
1.556     raeburn  10621:     var checkok = 1;
1.558     albertel 10622:     var srchin;
1.570     raeburn  10623:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10624: 	if ( callingForm.srchin[i].checked ) {
                   10625: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10626: 	}
                   10627:     }
                   10628: 
1.570     raeburn  10629:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10630:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10631:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10632:     var srchterm =  callingForm.srchterm.value;
                   10633:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10634:     var msg = "";
                   10635: 
                   10636:     if (srchterm == "") {
                   10637:         checkok = 0;
1.1222    damieng  10638:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10639:     }
                   10640: 
1.569     raeburn  10641:     if (srchtype== 'begins') {
                   10642:         if (srchterm.length < 2) {
                   10643:             checkok = 0;
1.1222    damieng  10644:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10645:         }
                   10646:     }
                   10647: 
1.556     raeburn  10648:     if (srchtype== 'contains') {
                   10649:         if (srchterm.length < 3) {
                   10650:             checkok = 0;
1.1222    damieng  10651:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10652:         }
                   10653:     }
                   10654:     if (srchin == 'instd') {
                   10655:         if (srchdomain == '') {
                   10656:             checkok = 0;
1.1222    damieng  10657:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10658:         }
                   10659:     }
                   10660:     if (srchin == 'dom') {
                   10661:         if (srchdomain == '') {
                   10662:             checkok = 0;
1.1222    damieng  10663:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10664:         }
                   10665:     }
                   10666:     if (srchby == 'lastfirst') {
                   10667:         if (srchterm.indexOf(",") == -1) {
                   10668:             checkok = 0;
1.1222    damieng  10669:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10670:         }
                   10671:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10672:             checkok = 0;
1.1222    damieng  10673:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10674:         }
                   10675:     }
                   10676:     if (checkok == 0) {
1.1222    damieng  10677:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10678:         return;
                   10679:     }
                   10680:     if (checkok == 1) {
1.570     raeburn  10681:         callingForm.submit();
1.556     raeburn  10682:     }
                   10683: }
                   10684: 
                   10685: $newuserscript
                   10686: 
1.824     bisitz   10687: // ]]>
1.556     raeburn  10688: </script>
1.558     albertel 10689: 
                   10690: $new_user_create
                   10691: 
1.555     raeburn  10692: END_BLOCK
1.558     albertel 10693: 
1.876     raeburn  10694:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10695:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10696:                $domform.
                   10697:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10698:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10699:                $srchbysel.
                   10700:                $srchtypesel. 
                   10701:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10702:                $srchinsel.
                   10703:                &Apache::lonhtmlcommon::row_closure(1). 
                   10704:                &Apache::lonhtmlcommon::end_pick_box().
                   10705:                '<br />';
1.1253    raeburn  10706:     return ($output,1);
1.555     raeburn  10707: }
                   10708: 
1.612     raeburn  10709: sub user_rule_check {
1.615     raeburn  10710:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10711:     my ($response,%inst_response);
1.612     raeburn  10712:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10713:         if (keys(%{$usershash}) > 1) {
                   10714:             my (%by_username,%by_id,%userdoms);
                   10715:             my $checkid; 
                   10716:             if (ref($checks) eq 'HASH') {
                   10717:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10718:                     $checkid = 1;
                   10719:                 }
                   10720:             }
                   10721:             foreach my $user (keys(%{$usershash})) {
                   10722:                 my ($uname,$udom) = split(/:/,$user);
                   10723:                 if ($checkid) {
                   10724:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10725:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10726:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10727:                             $userdoms{$udom} = 1;
1.1227    raeburn  10728:                             if (ref($inst_results) eq 'HASH') {
                   10729:                                 $inst_results->{$uname.':'.$udom} = {};
                   10730:                             }
1.1226    raeburn  10731:                         }
                   10732:                     }
                   10733:                 } else {
                   10734:                     $by_username{$udom}{$uname} = 1;
                   10735:                     $userdoms{$udom} = 1;
1.1227    raeburn  10736:                     if (ref($inst_results) eq 'HASH') {
                   10737:                         $inst_results->{$uname.':'.$udom} = {};
                   10738:                     }
1.1226    raeburn  10739:                 }
                   10740:             }
                   10741:             foreach my $udom (keys(%userdoms)) {
                   10742:                 if (!$got_rules->{$udom}) {
                   10743:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10744:                                                              ['usercreation'],$udom);
                   10745:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10746:                         foreach my $item ('username','id') {
                   10747:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10748:                                 $$curr_rules{$udom}{$item} =
                   10749:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10750:                             }
                   10751:                         }
                   10752:                     }
                   10753:                     $got_rules->{$udom} = 1;
                   10754:                 }
1.612     raeburn  10755:             }
1.1226    raeburn  10756:             if ($checkid) {
                   10757:                 foreach my $udom (keys(%by_id)) {
                   10758:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10759:                     if ($outcome eq 'ok') {
1.1227    raeburn  10760:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10761:                             my $uname = $by_id{$udom}{$id};
                   10762:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10763:                         }
1.1226    raeburn  10764:                         if (ref($results) eq 'HASH') {
                   10765:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10766:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10767:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10768:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10769:                                 }
1.1226    raeburn  10770:                             }
                   10771:                         }
                   10772:                     }
1.612     raeburn  10773:                 }
1.615     raeburn  10774:             } else {
1.1226    raeburn  10775:                 foreach my $udom (keys(%by_username)) {
                   10776:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10777:                     if ($outcome eq 'ok') {
1.1227    raeburn  10778:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10779:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10780:                         }
1.1226    raeburn  10781:                         if (ref($results) eq 'HASH') {
                   10782:                             foreach my $uname (keys(%{$results})) {
                   10783:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10784:                             }
                   10785:                         }
                   10786:                     }
                   10787:                 }
1.612     raeburn  10788:             }
1.1226    raeburn  10789:         } elsif (keys(%{$usershash}) == 1) {
                   10790:             my $user = (keys(%{$usershash}))[0];
                   10791:             my ($uname,$udom) = split(/:/,$user);
                   10792:             if (($udom ne '') && ($uname ne '')) {
                   10793:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10794:                     if (ref($checks) eq 'HASH') {
                   10795:                         if (defined($checks->{'username'})) {
                   10796:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10797:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10798:                         } elsif (defined($checks->{'id'})) {
                   10799:                             if ($usershash->{$user}->{'id'} ne '') {
                   10800:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10801:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10802:                                                                   $usershash->{$user}->{'id'});
                   10803:                             } else {
                   10804:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10805:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10806:                             }
1.585     raeburn  10807:                         }
1.1226    raeburn  10808:                     } else {
                   10809:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10810:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10811:                        return;
                   10812:                     }
                   10813:                     if (!$got_rules->{$udom}) {
                   10814:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10815:                                                                  ['usercreation'],$udom);
                   10816:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10817:                             foreach my $item ('username','id') {
                   10818:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10819:                                    $$curr_rules{$udom}{$item} = 
                   10820:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10821:                                 }
                   10822:                             }
                   10823:                         }
                   10824:                         $got_rules->{$udom} = 1;
1.585     raeburn  10825:                     }
                   10826:                 }
1.1226    raeburn  10827:             } else {
                   10828:                 return;
                   10829:             }
                   10830:         } else {
                   10831:             return;
                   10832:         }
                   10833:         foreach my $user (keys(%{$usershash})) {
                   10834:             my ($uname,$udom) = split(/:/,$user);
                   10835:             next if (($udom eq '') || ($uname eq ''));
                   10836:             my $id;
1.1227    raeburn  10837:             if (ref($inst_results) eq 'HASH') {
                   10838:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10839:                     $id = $inst_results->{$user}->{'id'};
                   10840:                 }
                   10841:             }
                   10842:             if ($id eq '') { 
                   10843:                 if (ref($usershash->{$user})) {
                   10844:                     $id = $usershash->{$user}->{'id'};
                   10845:                 }
1.585     raeburn  10846:             }
1.612     raeburn  10847:             foreach my $item (keys(%{$checks})) {
                   10848:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10849:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10850:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10851:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10852:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10853:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10854:                                 if ($rule_check{$rule}) {
                   10855:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10856:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10857:                                         if (ref($inst_results) eq 'HASH') {
                   10858:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10859:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10860:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10861:                                                 } elsif ($item eq 'id') {
                   10862:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10863:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10864:                                                     }
1.615     raeburn  10865:                                                 }
1.612     raeburn  10866:                                             }
                   10867:                                         }
1.615     raeburn  10868:                                     }
                   10869:                                     last;
1.585     raeburn  10870:                                 }
                   10871:                             }
                   10872:                         }
                   10873:                     }
                   10874:                 }
                   10875:             }
                   10876:         }
                   10877:     }
1.612     raeburn  10878:     return;
                   10879: }
                   10880: 
                   10881: sub user_rule_formats {
                   10882:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10883:     my %text = ( 
                   10884:                  'username' => 'Usernames',
                   10885:                  'id'       => 'IDs',
                   10886:                );
                   10887:     my $output;
                   10888:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10889:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10890:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10891:             $output = '<br />'.
                   10892:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10893:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10894:                       ' <ul>';
1.612     raeburn  10895:             foreach my $rule (@{$ruleorder}) {
                   10896:                 if (ref($curr_rules) eq 'ARRAY') {
                   10897:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10898:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10899:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10900:                                         $rules->{$rule}{'desc'}.'</li>';
                   10901:                         }
                   10902:                     }
                   10903:                 }
                   10904:             }
                   10905:             $output .= '</ul>';
                   10906:         }
                   10907:     }
                   10908:     return $output;
                   10909: }
                   10910: 
                   10911: sub instrule_disallow_msg {
1.615     raeburn  10912:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10913:     my $response;
                   10914:     my %text = (
                   10915:                   item   => 'username',
                   10916:                   items  => 'usernames',
                   10917:                   match  => 'matches',
                   10918:                   do     => 'does',
                   10919:                   action => 'a username',
                   10920:                   one    => 'one',
                   10921:                );
                   10922:     if ($count > 1) {
                   10923:         $text{'item'} = 'usernames';
                   10924:         $text{'match'} ='match';
                   10925:         $text{'do'} = 'do';
                   10926:         $text{'action'} = 'usernames',
                   10927:         $text{'one'} = 'ones';
                   10928:     }
                   10929:     if ($checkitem eq 'id') {
                   10930:         $text{'items'} = 'IDs';
                   10931:         $text{'item'} = 'ID';
                   10932:         $text{'action'} = 'an ID';
1.615     raeburn  10933:         if ($count > 1) {
                   10934:             $text{'item'} = 'IDs';
                   10935:             $text{'action'} = 'IDs';
                   10936:         }
1.612     raeburn  10937:     }
1.674     bisitz   10938:     $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  10939:     if ($mode eq 'upload') {
                   10940:         if ($checkitem eq 'username') {
                   10941:             $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'}.");
                   10942:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10943:             $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  10944:         }
1.669     raeburn  10945:     } elsif ($mode eq 'selfcreate') {
                   10946:         if ($checkitem eq 'id') {
                   10947:             $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.");
                   10948:         }
1.615     raeburn  10949:     } else {
                   10950:         if ($checkitem eq 'username') {
                   10951:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10952:         } elsif ($checkitem eq 'id') {
                   10953:             $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.");
                   10954:         }
1.612     raeburn  10955:     }
                   10956:     return $response;
1.585     raeburn  10957: }
                   10958: 
1.624     raeburn  10959: sub personal_data_fieldtitles {
                   10960:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10961:                         id => 'Student/Employee ID',
                   10962:                         permanentemail => 'E-mail address',
                   10963:                         lastname => 'Last Name',
                   10964:                         firstname => 'First Name',
                   10965:                         middlename => 'Middle Name',
                   10966:                         generation => 'Generation',
                   10967:                         gen => 'Generation',
1.765     raeburn  10968:                         inststatus => 'Affiliation',
1.624     raeburn  10969:                    );
                   10970:     return %fieldtitles;
                   10971: }
                   10972: 
1.642     raeburn  10973: sub sorted_inst_types {
                   10974:     my ($dom) = @_;
1.1185    raeburn  10975:     my ($usertypes,$order);
                   10976:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10977:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10978:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10979:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10980:     } else {
                   10981:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10982:     }
1.642     raeburn  10983:     my $othertitle = &mt('All users');
                   10984:     if ($env{'request.course.id'}) {
1.668     raeburn  10985:         $othertitle  = &mt('Any users');
1.642     raeburn  10986:     }
                   10987:     my @types;
                   10988:     if (ref($order) eq 'ARRAY') {
                   10989:         @types = @{$order};
                   10990:     }
                   10991:     if (@types == 0) {
                   10992:         if (ref($usertypes) eq 'HASH') {
                   10993:             @types = sort(keys(%{$usertypes}));
                   10994:         }
                   10995:     }
                   10996:     if (keys(%{$usertypes}) > 0) {
                   10997:         $othertitle = &mt('Other users');
                   10998:     }
                   10999:     return ($othertitle,$usertypes,\@types);
                   11000: }
                   11001: 
1.645     raeburn  11002: sub get_institutional_codes {
                   11003:     my ($settings,$allcourses,$LC_code) = @_;
                   11004: # Get complete list of course sections to update
                   11005:     my @currsections = ();
                   11006:     my @currxlists = ();
                   11007:     my $coursecode = $$settings{'internal.coursecode'};
                   11008: 
                   11009:     if ($$settings{'internal.sectionnums'} ne '') {
                   11010:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11011:     }
                   11012: 
                   11013:     if ($$settings{'internal.crosslistings'} ne '') {
                   11014:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11015:     }
                   11016: 
                   11017:     if (@currxlists > 0) {
                   11018:         foreach (@currxlists) {
                   11019:             if (m/^([^:]+):(\w*)$/) {
                   11020:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11021:                     push(@{$allcourses},$1);
1.645     raeburn  11022:                     $$LC_code{$1} = $2;
                   11023:                 }
                   11024:             }
                   11025:         }
                   11026:     }
                   11027:  
                   11028:     if (@currsections > 0) {
                   11029:         foreach (@currsections) {
                   11030:             if (m/^(\w+):(\w*)$/) {
                   11031:                 my $sec = $coursecode.$1;
                   11032:                 my $lc_sec = $2;
                   11033:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  11034:                     push(@{$allcourses},$sec);
1.645     raeburn  11035:                     $$LC_code{$sec} = $lc_sec;
                   11036:                 }
                   11037:             }
                   11038:         }
                   11039:     }
                   11040:     return;
                   11041: }
                   11042: 
1.971     raeburn  11043: sub get_standard_codeitems {
                   11044:     return ('Year','Semester','Department','Number','Section');
                   11045: }
                   11046: 
1.112     bowersj2 11047: =pod
                   11048: 
1.780     raeburn  11049: =head1 Slot Helpers
                   11050: 
                   11051: =over 4
                   11052: 
                   11053: =item * sorted_slots()
                   11054: 
1.1040    raeburn  11055: Sorts an array of slot names in order of an optional sort key,
                   11056: default sort is by slot start time (earliest first). 
1.780     raeburn  11057: 
                   11058: Inputs:
                   11059: 
                   11060: =over 4
                   11061: 
                   11062: slotsarr  - Reference to array of unsorted slot names.
                   11063: 
                   11064: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11065: 
1.1040    raeburn  11066: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11067: 
1.549     albertel 11068: =back
                   11069: 
1.780     raeburn  11070: Returns:
                   11071: 
                   11072: =over 4
                   11073: 
1.1040    raeburn  11074: sorted   - An array of slot names sorted by a specified sort key 
                   11075:            (default sort key is start time of the slot).
1.780     raeburn  11076: 
                   11077: =back
                   11078: 
                   11079: =cut
                   11080: 
                   11081: 
                   11082: sub sorted_slots {
1.1040    raeburn  11083:     my ($slotsarr,$slots,$sortkey) = @_;
                   11084:     if ($sortkey eq '') {
                   11085:         $sortkey = 'starttime';
                   11086:     }
1.780     raeburn  11087:     my @sorted;
                   11088:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11089:         @sorted =
                   11090:             sort {
                   11091:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11092:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11093:                      }
                   11094:                      if (ref($slots->{$a})) { return -1;}
                   11095:                      if (ref($slots->{$b})) { return 1;}
                   11096:                      return 0;
                   11097:                  } @{$slotsarr};
                   11098:     }
                   11099:     return @sorted;
                   11100: }
                   11101: 
1.1040    raeburn  11102: =pod
                   11103: 
                   11104: =item * get_future_slots()
                   11105: 
                   11106: Inputs:
                   11107: 
                   11108: =over 4
                   11109: 
                   11110: cnum - course number
                   11111: 
                   11112: cdom - course domain
                   11113: 
                   11114: now - current UNIX time
                   11115: 
                   11116: symb - optional symb
                   11117: 
                   11118: =back
                   11119: 
                   11120: Returns:
                   11121: 
                   11122: =over 4
                   11123: 
                   11124: sorted_reservable - ref to array of student_schedulable slots currently 
                   11125:                     reservable, ordered by end date of reservation period.
                   11126: 
                   11127: reservable_now - ref to hash of student_schedulable slots currently
                   11128:                  reservable.
                   11129: 
                   11130:     Keys in inner hash are:
                   11131:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11132:     (b) endreserve: end date of reservation period.
                   11133:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11134:         selected.
1.1040    raeburn  11135: 
                   11136: sorted_future - ref to array of student_schedulable slots reservable in
                   11137:                 the future, ordered by start date of reservation period.
                   11138: 
                   11139: future_reservable - ref to hash of student_schedulable slots reservable
                   11140:                     in the future.
                   11141: 
                   11142:     Keys in inner hash are:
                   11143:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11144:     (b) startreserve: start date of reservation period.
                   11145:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11146:         selected.
1.1040    raeburn  11147: 
                   11148: =back
                   11149: 
                   11150: =cut
                   11151: 
                   11152: sub get_future_slots {
                   11153:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11154:     my $map;
                   11155:     if ($symb) {
                   11156:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11157:     }
1.1040    raeburn  11158:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11159:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11160:     foreach my $slot (keys(%slots)) {
                   11161:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11162:         if ($symb) {
1.1229    raeburn  11163:             if ($slots{$slot}->{'symb'} ne '') {
                   11164:                 my $canuse;
                   11165:                 my %oksymbs;
                   11166:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11167:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11168:                 if ($oksymbs{$symb}) {
                   11169:                     $canuse = 1;
                   11170:                 } else {
                   11171:                     foreach my $item (@slotsymbs) {
                   11172:                         if ($item =~ /\.(page|sequence)$/) {
                   11173:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11174:                             if (($map ne '') && ($map eq $sloturl)) {
                   11175:                                 $canuse = 1;
                   11176:                                 last;
                   11177:                             }
                   11178:                         }
                   11179:                     }
                   11180:                 }
                   11181:                 next unless ($canuse);
                   11182:             }
1.1040    raeburn  11183:         }
                   11184:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11185:             ($slots{$slot}->{'endtime'} > $now)) {
                   11186:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11187:                 my $userallowed = 0;
                   11188:                 if ($slots{$slot}->{'allowedsections'}) {
                   11189:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11190:                     if (!defined($env{'request.role.sec'})
                   11191:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11192:                         $userallowed=1;
                   11193:                     } else {
                   11194:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11195:                             $userallowed=1;
                   11196:                         }
                   11197:                     }
                   11198:                     unless ($userallowed) {
                   11199:                         if (defined($env{'request.course.groups'})) {
                   11200:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11201:                             foreach my $group (@groups) {
                   11202:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11203:                                     $userallowed=1;
                   11204:                                     last;
                   11205:                                 }
                   11206:                             }
                   11207:                         }
                   11208:                     }
                   11209:                 }
                   11210:                 if ($slots{$slot}->{'allowedusers'}) {
                   11211:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11212:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11213:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11214:                         $userallowed = 1;
                   11215:                     }
                   11216:                 }
                   11217:                 next unless($userallowed);
                   11218:             }
                   11219:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11220:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11221:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11222:             my $uniqueperiod;
                   11223:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11224:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11225:             }
1.1040    raeburn  11226:             if (($startreserve < $now) &&
                   11227:                 (!$endreserve || $endreserve > $now)) {
                   11228:                 my $lastres = $endreserve;
                   11229:                 if (!$lastres) {
                   11230:                     $lastres = $slots{$slot}->{'starttime'};
                   11231:                 }
                   11232:                 $reservable_now{$slot} = {
                   11233:                                            symb       => $symb,
1.1250    raeburn  11234:                                            endreserve => $lastres,
                   11235:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11236:                                          };
                   11237:             } elsif (($startreserve > $now) &&
                   11238:                      (!$endreserve || $endreserve > $startreserve)) {
                   11239:                 $future_reservable{$slot} = {
                   11240:                                               symb         => $symb,
1.1250    raeburn  11241:                                               startreserve => $startreserve,
                   11242:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11243:                                             };
                   11244:             }
                   11245:         }
                   11246:     }
                   11247:     my @unsorted_reservable = keys(%reservable_now);
                   11248:     if (@unsorted_reservable > 0) {
                   11249:         @sorted_reservable = 
                   11250:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11251:     }
                   11252:     my @unsorted_future = keys(%future_reservable);
                   11253:     if (@unsorted_future > 0) {
                   11254:         @sorted_future =
                   11255:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11256:     }
                   11257:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11258: }
1.780     raeburn  11259: 
                   11260: =pod
                   11261: 
1.1057    foxr     11262: =back
                   11263: 
1.549     albertel 11264: =head1 HTTP Helpers
                   11265: 
                   11266: =over 4
                   11267: 
1.648     raeburn  11268: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11269: 
1.258     albertel 11270: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11271: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11272: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11273: 
                   11274: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11275: $possible_names is an ref to an array of form element names.  As an example:
                   11276: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11277: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11278: 
                   11279: =cut
1.1       albertel 11280: 
1.6       albertel 11281: sub get_unprocessed_cgi {
1.25      albertel 11282:   my ($query,$possible_names)= @_;
1.26      matthew  11283:   # $Apache::lonxml::debug=1;
1.356     albertel 11284:   foreach my $pair (split(/&/,$query)) {
                   11285:     my ($name, $value) = split(/=/,$pair);
1.369     www      11286:     $name = &unescape($name);
1.25      albertel 11287:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11288:       $value =~ tr/+/ /;
                   11289:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11290:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11291:     }
1.16      harris41 11292:   }
1.6       albertel 11293: }
                   11294: 
1.112     bowersj2 11295: =pod
                   11296: 
1.648     raeburn  11297: =item * &cacheheader() 
1.112     bowersj2 11298: 
                   11299: returns cache-controlling header code
                   11300: 
                   11301: =cut
                   11302: 
1.7       albertel 11303: sub cacheheader {
1.258     albertel 11304:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11305:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11306:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11307:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11308:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11309:     return $output;
1.7       albertel 11310: }
                   11311: 
1.112     bowersj2 11312: =pod
                   11313: 
1.648     raeburn  11314: =item * &no_cache($r) 
1.112     bowersj2 11315: 
                   11316: specifies header code to not have cache
                   11317: 
                   11318: =cut
                   11319: 
1.9       albertel 11320: sub no_cache {
1.216     albertel 11321:     my ($r) = @_;
                   11322:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11323: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11324:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11325:     $r->no_cache(1);
                   11326:     $r->header_out("Expires" => $date);
                   11327:     $r->header_out("Pragma" => "no-cache");
1.123     www      11328: }
                   11329: 
                   11330: sub content_type {
1.181     albertel 11331:     my ($r,$type,$charset) = @_;
1.299     foxr     11332:     if ($r) {
                   11333: 	#  Note that printout.pl calls this with undef for $r.
                   11334: 	&no_cache($r);
                   11335:     }
1.258     albertel 11336:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11337:     unless ($charset) {
                   11338: 	$charset=&Apache::lonlocal::current_encoding;
                   11339:     }
                   11340:     if ($charset) { $type.='; charset='.$charset; }
                   11341:     if ($r) {
                   11342: 	$r->content_type($type);
                   11343:     } else {
                   11344: 	print("Content-type: $type\n\n");
                   11345:     }
1.9       albertel 11346: }
1.25      albertel 11347: 
1.112     bowersj2 11348: =pod
                   11349: 
1.648     raeburn  11350: =item * &add_to_env($name,$value) 
1.112     bowersj2 11351: 
1.258     albertel 11352: adds $name to the %env hash with value
1.112     bowersj2 11353: $value, if $name already exists, the entry is converted to an array
                   11354: reference and $value is added to the array.
                   11355: 
                   11356: =cut
                   11357: 
1.25      albertel 11358: sub add_to_env {
                   11359:   my ($name,$value)=@_;
1.258     albertel 11360:   if (defined($env{$name})) {
                   11361:     if (ref($env{$name})) {
1.25      albertel 11362:       #already have multiple values
1.258     albertel 11363:       push(@{ $env{$name} },$value);
1.25      albertel 11364:     } else {
                   11365:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11366:       my $first=$env{$name};
                   11367:       undef($env{$name});
                   11368:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11369:     }
                   11370:   } else {
1.258     albertel 11371:     $env{$name}=$value;
1.25      albertel 11372:   }
1.31      albertel 11373: }
1.149     albertel 11374: 
                   11375: =pod
                   11376: 
1.648     raeburn  11377: =item * &get_env_multiple($name) 
1.149     albertel 11378: 
1.258     albertel 11379: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11380: values may be defined and end up as an array ref.
                   11381: 
                   11382: returns an array of values
                   11383: 
                   11384: =cut
                   11385: 
                   11386: sub get_env_multiple {
                   11387:     my ($name) = @_;
                   11388:     my @values;
1.258     albertel 11389:     if (defined($env{$name})) {
1.149     albertel 11390:         # exists is it an array
1.258     albertel 11391:         if (ref($env{$name})) {
                   11392:             @values=@{ $env{$name} };
1.149     albertel 11393:         } else {
1.258     albertel 11394:             $values[0]=$env{$name};
1.149     albertel 11395:         }
                   11396:     }
                   11397:     return(@values);
                   11398: }
                   11399: 
1.1249    damieng  11400: # Looks at given dependencies, and returns something depending on the context.
                   11401: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11402: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11403: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11404: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11405: # $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.
                   11406: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11407: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11408: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11409: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11410: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11411: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11412: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11413: # @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)
                   11414: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11415: sub ask_for_embedded_content {
1.1249    damieng  11416:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11417:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11418:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11419:         %currsubfile,%unused,$rem);
1.1071    raeburn  11420:     my $counter = 0;
                   11421:     my $numnew = 0;
1.987     raeburn  11422:     my $numremref = 0;
                   11423:     my $numinvalid = 0;
                   11424:     my $numpathchg = 0;
                   11425:     my $numexisting = 0;
1.1071    raeburn  11426:     my $numunused = 0;
                   11427:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11428:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11429:     my $heading = &mt('Upload embedded files');
                   11430:     my $buttontext = &mt('Upload');
                   11431: 
1.1249    damieng  11432:     # fills these variables based on the context:
                   11433:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11434:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11435:     if ($env{'request.course.id'}) {
1.1123    raeburn  11436:         if ($actionurl eq '/adm/dependencies') {
                   11437:             $navmap = Apache::lonnavmaps::navmap->new();
                   11438:         }
                   11439:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11440:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11441:     }
1.1123    raeburn  11442:     if (($actionurl eq '/adm/portfolio') || 
                   11443:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11444:         my $current_path='/';
                   11445:         if ($env{'form.currentpath'}) {
                   11446:             $current_path = $env{'form.currentpath'};
                   11447:         }
                   11448:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11449:             $udom = $cdom;
                   11450:             $uname = $cnum;
1.984     raeburn  11451:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11452:         } else {
                   11453:             $udom = $env{'user.domain'};
                   11454:             $uname = $env{'user.name'};
                   11455:             $url = '/userfiles/portfolio';
                   11456:         }
1.987     raeburn  11457:         $toplevel = $url.'/';
1.984     raeburn  11458:         $url .= $current_path;
                   11459:         $getpropath = 1;
1.987     raeburn  11460:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11461:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11462:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11463:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11464:         $toplevel = $url;
1.984     raeburn  11465:         if ($rest ne '') {
1.987     raeburn  11466:             $url .= $rest;
                   11467:         }
                   11468:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11469:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11470:             $url = $args->{'docs_url'};
                   11471:             $toplevel = $url;
1.1084    raeburn  11472:             if ($args->{'context'} eq 'paste') {
                   11473:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11474:                 ($path) = 
                   11475:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11476:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11477:                 $fileloc =~ s{^/}{};
                   11478:             }
1.1071    raeburn  11479:         }
1.1084    raeburn  11480:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11481:         if ($env{'request.course.id'} ne '') {
                   11482:             if (ref($args) eq 'HASH') {
                   11483:                 $url = $args->{'docs_url'};
                   11484:                 $title = $args->{'docs_title'};
1.1126    raeburn  11485:                 $toplevel = $url; 
                   11486:                 unless ($toplevel =~ m{^/}) {
                   11487:                     $toplevel = "/$url";
                   11488:                 }
1.1085    raeburn  11489:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11490:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11491:                     $path = $1;
                   11492:                 } else {
                   11493:                     ($path) =
                   11494:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11495:                 }
1.1195    raeburn  11496:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11497:                     $fileloc = $toplevel;
                   11498:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11499:                     my ($udom,$uname,$fname) =
                   11500:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11501:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11502:                 } else {
                   11503:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11504:                 }
1.1071    raeburn  11505:                 $fileloc =~ s{^/}{};
                   11506:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11507:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11508:             }
1.987     raeburn  11509:         }
1.1123    raeburn  11510:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11511:         $udom = $cdom;
                   11512:         $uname = $cnum;
                   11513:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11514:         $toplevel = $url;
                   11515:         $path = $url;
                   11516:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11517:         $fileloc =~ s{^/}{};
1.987     raeburn  11518:     }
1.1249    damieng  11519:     
                   11520:     # parses the dependency paths to get some info
                   11521:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11522:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11523:     # (will be completed later)
                   11524:     # $mapping:
                   11525:     #   for external URLs: external URL -> external URL
                   11526:     #   for relative paths: clean path -> original path
                   11527:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11528:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11529:     foreach my $file (keys(%{$allfiles})) {
                   11530:         my $embed_file;
                   11531:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11532:             $embed_file = $1;
                   11533:         } else {
                   11534:             $embed_file = $file;
                   11535:         }
1.1158    raeburn  11536:         my ($absolutepath,$cleaned_file);
                   11537:         if ($embed_file =~ m{^\w+://}) {
                   11538:             $cleaned_file = $embed_file;
1.1147    raeburn  11539:             $newfiles{$cleaned_file} = 1;
                   11540:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11541:         } else {
1.1158    raeburn  11542:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11543:             if ($embed_file =~ m{^/}) {
                   11544:                 $absolutepath = $embed_file;
                   11545:             }
1.1147    raeburn  11546:             if ($cleaned_file =~ m{/}) {
                   11547:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11548:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11549:                 my $item = $fname;
                   11550:                 if ($path ne '') {
                   11551:                     $item = $path.'/'.$fname;
                   11552:                     $subdependencies{$path}{$fname} = 1;
                   11553:                 } else {
                   11554:                     $dependencies{$item} = 1;
                   11555:                 }
                   11556:                 if ($absolutepath) {
                   11557:                     $mapping{$item} = $absolutepath;
                   11558:                 } else {
                   11559:                     $mapping{$item} = $embed_file;
                   11560:                 }
                   11561:             } else {
                   11562:                 $dependencies{$embed_file} = 1;
                   11563:                 if ($absolutepath) {
1.1147    raeburn  11564:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11565:                 } else {
1.1147    raeburn  11566:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11567:                 }
                   11568:             }
1.984     raeburn  11569:         }
                   11570:     }
1.1249    damieng  11571:     
                   11572:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11573:     # and lists
                   11574:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11575:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11576:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11577:     #                                    the path had to be cleaned up
                   11578:     # $existing: hash clean path -> 1 if the file exists
                   11579:     # $numexisting: number of keys in $existing
                   11580:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11581:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11582:     #                                      dependency subdirectories that are
                   11583:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11584:     my $dirptr = 16384;
1.984     raeburn  11585:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11586:         $currsubfile{$path} = {};
1.1123    raeburn  11587:         if (($actionurl eq '/adm/portfolio') || 
                   11588:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11589:             my ($sublistref,$listerror) =
                   11590:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11591:             if (ref($sublistref) eq 'ARRAY') {
                   11592:                 foreach my $line (@{$sublistref}) {
                   11593:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11594:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11595:                 }
1.984     raeburn  11596:             }
1.987     raeburn  11597:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11598:             if (opendir(my $dir,$url.'/'.$path)) {
                   11599:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11600:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11601:             }
1.1084    raeburn  11602:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11603:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11604:                   ($args->{'context'} eq 'paste')) ||
                   11605:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11606:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11607:                 my $dir;
                   11608:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11609:                     $dir = $fileloc;
                   11610:                 } else {
                   11611:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11612:                 }
1.1071    raeburn  11613:                 if ($dir ne '') {
                   11614:                     my ($sublistref,$listerror) =
                   11615:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11616:                     if (ref($sublistref) eq 'ARRAY') {
                   11617:                         foreach my $line (@{$sublistref}) {
                   11618:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11619:                                 undef,$mtime)=split(/\&/,$line,12);
                   11620:                             unless (($testdir&$dirptr) ||
                   11621:                                     ($file_name =~ /^\.\.?$/)) {
                   11622:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11623:                             }
                   11624:                         }
                   11625:                     }
                   11626:                 }
1.984     raeburn  11627:             }
                   11628:         }
                   11629:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11630:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11631:                 my $item = $path.'/'.$file;
                   11632:                 unless ($mapping{$item} eq $item) {
                   11633:                     $pathchanges{$item} = 1;
                   11634:                 }
                   11635:                 $existing{$item} = 1;
                   11636:                 $numexisting ++;
                   11637:             } else {
                   11638:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11639:             }
                   11640:         }
1.1071    raeburn  11641:         if ($actionurl eq '/adm/dependencies') {
                   11642:             foreach my $path (keys(%currsubfile)) {
                   11643:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11644:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11645:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11646:                              next if (($rem ne '') &&
                   11647:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11648:                                        (ref($navmap) &&
                   11649:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11650:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11651:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11652:                              $unused{$path.'/'.$file} = 1; 
                   11653:                          }
                   11654:                     }
                   11655:                 }
                   11656:             }
                   11657:         }
1.984     raeburn  11658:     }
1.1249    damieng  11659:     
                   11660:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11661:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11662:     my %currfile;
1.1123    raeburn  11663:     if (($actionurl eq '/adm/portfolio') ||
                   11664:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11665:         my ($dirlistref,$listerror) =
                   11666:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11667:         if (ref($dirlistref) eq 'ARRAY') {
                   11668:             foreach my $line (@{$dirlistref}) {
                   11669:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11670:                 $currfile{$file_name} = 1;
                   11671:             }
1.984     raeburn  11672:         }
1.987     raeburn  11673:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11674:         if (opendir(my $dir,$url)) {
1.987     raeburn  11675:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11676:             map {$currfile{$_} = 1;} @dir_list;
                   11677:         }
1.1084    raeburn  11678:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11679:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11680:               ($args->{'context'} eq 'paste')) ||
                   11681:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11682:         if ($env{'request.course.id'} ne '') {
                   11683:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11684:             if ($dir ne '') {
                   11685:                 my ($dirlistref,$listerror) =
                   11686:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11687:                 if (ref($dirlistref) eq 'ARRAY') {
                   11688:                     foreach my $line (@{$dirlistref}) {
                   11689:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11690:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11691:                         unless (($testdir&$dirptr) ||
                   11692:                                 ($file_name =~ /^\.\.?$/)) {
                   11693:                             $currfile{$file_name} = [$size,$mtime];
                   11694:                         }
                   11695:                     }
                   11696:                 }
                   11697:             }
                   11698:         }
1.984     raeburn  11699:     }
1.1249    damieng  11700:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11701:     # are not in subdirectories, using $currfile
1.984     raeburn  11702:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11703:         if (exists($currfile{$file})) {
1.987     raeburn  11704:             unless ($mapping{$file} eq $file) {
                   11705:                 $pathchanges{$file} = 1;
                   11706:             }
                   11707:             $existing{$file} = 1;
                   11708:             $numexisting ++;
                   11709:         } else {
1.984     raeburn  11710:             $newfiles{$file} = 1;
                   11711:         }
                   11712:     }
1.1071    raeburn  11713:     foreach my $file (keys(%currfile)) {
                   11714:         unless (($file eq $filename) ||
                   11715:                 ($file eq $filename.'.bak') ||
                   11716:                 ($dependencies{$file})) {
1.1085    raeburn  11717:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11718:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11719:                     next if (($rem ne '') &&
                   11720:                              (($env{"httpref.$rem".$file} ne '') ||
                   11721:                               (ref($navmap) &&
                   11722:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11723:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11724:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11725:                 }
1.1085    raeburn  11726:             }
1.1071    raeburn  11727:             $unused{$file} = 1;
                   11728:         }
                   11729:     }
1.1249    damieng  11730:     
                   11731:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11732:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11733:         ($args->{'context'} eq 'paste')) {
                   11734:         $counter = scalar(keys(%existing));
                   11735:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11736:         return ($output,$counter,$numpathchg,\%existing);
                   11737:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11738:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11739:         $counter = scalar(keys(%existing));
                   11740:         $numpathchg = scalar(keys(%pathchanges));
                   11741:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11742:     }
1.1249    damieng  11743:     
                   11744:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11745:     
                   11746:     # $upload_output: missing dependencies (with upload form)
                   11747:     # $modify_output: uploaded dependencies (in use)
                   11748:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11749:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11750:         if ($actionurl eq '/adm/dependencies') {
                   11751:             next if ($embed_file =~ m{^\w+://});
                   11752:         }
1.660     raeburn  11753:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11754:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11755:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11756:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11757:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11758:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11759:         }
1.1123    raeburn  11760:         $upload_output .= '</td>';
1.1071    raeburn  11761:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11762:             $upload_output.='<td align="right">'.
                   11763:                             '<span class="LC_info LC_fontsize_medium">'.
                   11764:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11765:             $numremref++;
1.660     raeburn  11766:         } elsif ($args->{'error_on_invalid_names'}
                   11767:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11768:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11769:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11770:             $numinvalid++;
1.660     raeburn  11771:         } else {
1.1123    raeburn  11772:             $upload_output .= '<td>'.
                   11773:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11774:                                                      $embed_file,\%mapping,
1.1071    raeburn  11775:                                                      $allfiles,$codebase,'upload');
                   11776:             $counter ++;
                   11777:             $numnew ++;
1.987     raeburn  11778:         }
                   11779:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11780:     }
                   11781:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11782:         if ($actionurl eq '/adm/dependencies') {
                   11783:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11784:             $modify_output .= &start_data_table_row().
                   11785:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11786:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11787:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11788:                               '<td>'.$size.'</td>'.
                   11789:                               '<td>'.$mtime.'</td>'.
                   11790:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11791:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11792:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11793:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11794:                               &embedded_file_element('upload_embedded',$counter,
                   11795:                                                      $embed_file,\%mapping,
                   11796:                                                      $allfiles,$codebase,'modify').
                   11797:                               '</div></td>'.
                   11798:                               &end_data_table_row()."\n";
                   11799:             $counter ++;
                   11800:         } else {
                   11801:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11802:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11803:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11804:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11805:                               &Apache::loncommon::end_data_table_row()."\n";
                   11806:         }
                   11807:     }
                   11808:     my $delidx = $counter;
                   11809:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11810:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11811:         $delete_output .= &start_data_table_row().
                   11812:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11813:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11814:                           '<td>'.$size.'</td>'.
                   11815:                           '<td>'.$mtime.'</td>'.
                   11816:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11817:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11818:                           &embedded_file_element('upload_embedded',$delidx,
                   11819:                                                  $oldfile,\%mapping,$allfiles,
                   11820:                                                  $codebase,'delete').'</td>'.
                   11821:                           &end_data_table_row()."\n"; 
                   11822:         $numunused ++;
                   11823:         $delidx ++;
1.987     raeburn  11824:     }
                   11825:     if ($upload_output) {
                   11826:         $upload_output = &start_data_table().
                   11827:                          $upload_output.
                   11828:                          &end_data_table()."\n";
                   11829:     }
1.1071    raeburn  11830:     if ($modify_output) {
                   11831:         $modify_output = &start_data_table().
                   11832:                          &start_data_table_header_row().
                   11833:                          '<th>'.&mt('File').'</th>'.
                   11834:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11835:                          '<th>'.&mt('Modified').'</th>'.
                   11836:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11837:                          &end_data_table_header_row().
                   11838:                          $modify_output.
                   11839:                          &end_data_table()."\n";
                   11840:     }
                   11841:     if ($delete_output) {
                   11842:         $delete_output = &start_data_table().
                   11843:                          &start_data_table_header_row().
                   11844:                          '<th>'.&mt('File').'</th>'.
                   11845:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11846:                          '<th>'.&mt('Modified').'</th>'.
                   11847:                          '<th>'.&mt('Delete?').'</th>'.
                   11848:                          &end_data_table_header_row().
                   11849:                          $delete_output.
                   11850:                          &end_data_table()."\n";
                   11851:     }
1.987     raeburn  11852:     my $applies = 0;
                   11853:     if ($numremref) {
                   11854:         $applies ++;
                   11855:     }
                   11856:     if ($numinvalid) {
                   11857:         $applies ++;
                   11858:     }
                   11859:     if ($numexisting) {
                   11860:         $applies ++;
                   11861:     }
1.1071    raeburn  11862:     if ($counter || $numunused) {
1.987     raeburn  11863:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11864:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11865:                   $state.'<h3>'.$heading.'</h3>'; 
                   11866:         if ($actionurl eq '/adm/dependencies') {
                   11867:             if ($numnew) {
                   11868:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11869:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11870:                            $upload_output.'<br />'."\n";
                   11871:             }
                   11872:             if ($numexisting) {
                   11873:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11874:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11875:                            $modify_output.'<br />'."\n";
                   11876:                            $buttontext = &mt('Save changes');
                   11877:             }
                   11878:             if ($numunused) {
                   11879:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11880:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11881:                            $delete_output.'<br />'."\n";
                   11882:                            $buttontext = &mt('Save changes');
                   11883:             }
                   11884:         } else {
                   11885:             $output .= $upload_output.'<br />'."\n";
                   11886:         }
                   11887:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11888:                    $counter.'" />'."\n";
                   11889:         if ($actionurl eq '/adm/dependencies') { 
                   11890:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11891:                        $numnew.'" />'."\n";
                   11892:         } elsif ($actionurl eq '') {
1.987     raeburn  11893:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11894:         }
                   11895:     } elsif ($applies) {
                   11896:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11897:         if ($applies > 1) {
                   11898:             $output .=  
1.1123    raeburn  11899:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11900:             if ($numremref) {
                   11901:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11902:             }
                   11903:             if ($numinvalid) {
                   11904:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11905:             }
                   11906:             if ($numexisting) {
                   11907:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11908:             }
                   11909:             $output .= '</ul><br />';
                   11910:         } elsif ($numremref) {
                   11911:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11912:         } elsif ($numinvalid) {
                   11913:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11914:         } elsif ($numexisting) {
                   11915:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11916:         }
                   11917:         $output .= $upload_output.'<br />';
                   11918:     }
                   11919:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11920:     $chgcount = $counter;
1.987     raeburn  11921:     if (keys(%pathchanges) > 0) {
                   11922:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11923:             if ($counter) {
1.987     raeburn  11924:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11925:                                                   $embed_file,\%mapping,
1.1071    raeburn  11926:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11927:             } else {
                   11928:                 $pathchange_output .= 
                   11929:                     &start_data_table_row().
                   11930:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11931:                     $chgcount.'" checked="checked" /></td>'.
                   11932:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11933:                     '<td>'.$embed_file.
                   11934:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11935:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11936:                     '</td>'.&end_data_table_row();
1.660     raeburn  11937:             }
1.987     raeburn  11938:             $numpathchg ++;
                   11939:             $chgcount ++;
1.660     raeburn  11940:         }
                   11941:     }
1.1127    raeburn  11942:     if (($counter) || ($numunused)) {
1.987     raeburn  11943:         if ($numpathchg) {
                   11944:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11945:                        $numpathchg.'" />'."\n";
                   11946:         }
                   11947:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11948:             ($actionurl eq '/adm/imsimport')) {
                   11949:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11950:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11951:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11952:         } elsif ($actionurl eq '/adm/dependencies') {
                   11953:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11954:         }
1.1123    raeburn  11955:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11956:     } elsif ($numpathchg) {
                   11957:         my %pathchange = ();
                   11958:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11959:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11960:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11961:         }
1.987     raeburn  11962:     }
1.1071    raeburn  11963:     return ($output,$counter,$numpathchg);
1.987     raeburn  11964: }
                   11965: 
1.1147    raeburn  11966: =pod
                   11967: 
                   11968: =item * clean_path($name)
                   11969: 
                   11970: Performs clean-up of directories, subdirectories and filename in an
                   11971: embedded object, referenced in an HTML file which is being uploaded
                   11972: to a course or portfolio, where 
                   11973: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11974: checked.
                   11975: 
                   11976: Clean-up is similar to replacements in lonnet::clean_filename()
                   11977: except each / between sub-directory and next level is preserved.
                   11978: 
                   11979: =cut
                   11980: 
                   11981: sub clean_path {
                   11982:     my ($embed_file) = @_;
                   11983:     $embed_file =~s{^/+}{};
                   11984:     my @contents;
                   11985:     if ($embed_file =~ m{/}) {
                   11986:         @contents = split(/\//,$embed_file);
                   11987:     } else {
                   11988:         @contents = ($embed_file);
                   11989:     }
                   11990:     my $lastidx = scalar(@contents)-1;
                   11991:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11992:         $contents[$i]=~s{\\}{/}g;
                   11993:         $contents[$i]=~s/\s+/\_/g;
                   11994:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11995:         if ($i == $lastidx) {
                   11996:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11997:         }
                   11998:     }
                   11999:     if ($lastidx > 0) {
                   12000:         return join('/',@contents);
                   12001:     } else {
                   12002:         return $contents[0];
                   12003:     }
                   12004: }
                   12005: 
1.987     raeburn  12006: sub embedded_file_element {
1.1071    raeburn  12007:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12008:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12009:                    (ref($codebase) eq 'HASH'));
                   12010:     my $output;
1.1071    raeburn  12011:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12012:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12013:     }
                   12014:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12015:                &escape($embed_file).'" />';
                   12016:     unless (($context eq 'upload_embedded') && 
                   12017:             ($mapping->{$embed_file} eq $embed_file)) {
                   12018:         $output .='
                   12019:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12020:     }
                   12021:     my $attrib;
                   12022:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12023:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12024:     }
                   12025:     $output .=
                   12026:         "\n\t\t".
                   12027:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12028:         $attrib.'" />';
                   12029:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12030:         $output .=
                   12031:             "\n\t\t".
                   12032:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12033:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12034:     }
1.987     raeburn  12035:     return $output;
1.660     raeburn  12036: }
                   12037: 
1.1071    raeburn  12038: sub get_dependency_details {
                   12039:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12040:     my ($size,$mtime,$showsize,$showmtime);
                   12041:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12042:         if ($embed_file =~ m{/}) {
                   12043:             my ($path,$fname) = split(/\//,$embed_file);
                   12044:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12045:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12046:             }
                   12047:         } else {
                   12048:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12049:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12050:             }
                   12051:         }
                   12052:         $showsize = $size/1024.0;
                   12053:         $showsize = sprintf("%.1f",$showsize);
                   12054:         if ($mtime > 0) {
                   12055:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12056:         }
                   12057:     }
                   12058:     return ($showsize,$showmtime);
                   12059: }
                   12060: 
                   12061: sub ask_embedded_js {
                   12062:     return <<"END";
                   12063: <script type="text/javascript"">
                   12064: // <![CDATA[
                   12065: function toggleBrowse(counter) {
                   12066:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12067:     var fileid = document.getElementById('embedded_item_'+counter);
                   12068:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12069:     if (chkboxid.checked == true) {
                   12070:         uploaddivid.style.display='block';
                   12071:     } else {
                   12072:         uploaddivid.style.display='none';
                   12073:         fileid.value = '';
                   12074:     }
                   12075: }
                   12076: // ]]>
                   12077: </script>
                   12078: 
                   12079: END
                   12080: }
                   12081: 
1.661     raeburn  12082: sub upload_embedded {
                   12083:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12084:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12085:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12086:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12087:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12088:         my $orig_uploaded_filename =
                   12089:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12090:         foreach my $type ('orig','ref','attrib','codebase') {
                   12091:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12092:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12093:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12094:             }
                   12095:         }
1.661     raeburn  12096:         my ($path,$fname) =
                   12097:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12098:         # no path, whole string is fname
                   12099:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12100:         $fname = &Apache::lonnet::clean_filename($fname);
                   12101:         # See if there is anything left
                   12102:         next if ($fname eq '');
                   12103: 
                   12104:         # Check if file already exists as a file or directory.
                   12105:         my ($state,$msg);
                   12106:         if ($context eq 'portfolio') {
                   12107:             my $port_path = $dirpath;
                   12108:             if ($group ne '') {
                   12109:                 $port_path = "groups/$group/$port_path";
                   12110:             }
1.987     raeburn  12111:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12112:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12113:                                               $dir_root,$port_path,$disk_quota,
                   12114:                                               $current_disk_usage,$uname,$udom);
                   12115:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12116:                 || $state eq 'file_locked') {
1.661     raeburn  12117:                 $output .= $msg;
                   12118:                 next;
                   12119:             }
                   12120:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12121:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12122:             if ($state eq 'exists') {
                   12123:                 $output .= $msg;
                   12124:                 next;
                   12125:             }
                   12126:         }
                   12127:         # Check if extension is valid
                   12128:         if (($fname =~ /\.(\w+)$/) &&
                   12129:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12130:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12131:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12132:             next;
                   12133:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12134:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12135:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12136:             next;
                   12137:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12138:             $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  12139:             next;
                   12140:         }
                   12141:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12142:         my $subdir = $path;
                   12143:         $subdir =~ s{/+$}{};
1.661     raeburn  12144:         if ($context eq 'portfolio') {
1.984     raeburn  12145:             my $result;
                   12146:             if ($state eq 'existingfile') {
                   12147:                 $result=
                   12148:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12149:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12150:             } else {
1.984     raeburn  12151:                 $result=
                   12152:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12153:                                                     $dirpath.
1.1123    raeburn  12154:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12155:                 if ($result !~ m|^/uploaded/|) {
                   12156:                     $output .= '<span class="LC_error">'
                   12157:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12158:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12159:                                .'</span><br />';
                   12160:                     next;
                   12161:                 } else {
1.987     raeburn  12162:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12163:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12164:                 }
1.661     raeburn  12165:             }
1.1123    raeburn  12166:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12167:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12168:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12169:             my $result =
1.1126    raeburn  12170:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12171:             if ($result !~ m|^/uploaded/|) {
                   12172:                 $output .= '<span class="LC_error">'
                   12173:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12174:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12175:                            .'</span><br />';
                   12176:                     next;
                   12177:             } else {
                   12178:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12179:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12180:                 if ($context eq 'syllabus') {
                   12181:                     &Apache::lonnet::make_public_indefinitely($result);
                   12182:                 }
1.987     raeburn  12183:             }
1.661     raeburn  12184:         } else {
                   12185: # Save the file
                   12186:             my $target = $env{'form.embedded_item_'.$i};
                   12187:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12188:             my $dest = $fullpath.$fname;
                   12189:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12190:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12191:             my $count;
                   12192:             my $filepath = $dir_root;
1.1027    raeburn  12193:             foreach my $subdir (@parts) {
                   12194:                 $filepath .= "/$subdir";
                   12195:                 if (!-e $filepath) {
1.661     raeburn  12196:                     mkdir($filepath,0770);
                   12197:                 }
                   12198:             }
                   12199:             my $fh;
                   12200:             if (!open($fh,'>'.$dest)) {
                   12201:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12202:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12203:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12204:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12205:                            '</span><br />';
                   12206:             } else {
                   12207:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12208:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12209:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12210:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12211:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12212:                               '</span><br />';
                   12213:                 } else {
1.987     raeburn  12214:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12215:                                $url.'</span>').'<br />';
                   12216:                     unless ($context eq 'testbank') {
                   12217:                         $footer .= &mt('View embedded file: [_1]',
                   12218:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12219:                     }
                   12220:                 }
                   12221:                 close($fh);
                   12222:             }
                   12223:         }
                   12224:         if ($env{'form.embedded_ref_'.$i}) {
                   12225:             $pathchange{$i} = 1;
                   12226:         }
                   12227:     }
                   12228:     if ($output) {
                   12229:         $output = '<p>'.$output.'</p>';
                   12230:     }
                   12231:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12232:     $returnflag = 'ok';
1.1071    raeburn  12233:     my $numpathchgs = scalar(keys(%pathchange));
                   12234:     if ($numpathchgs > 0) {
1.987     raeburn  12235:         if ($context eq 'portfolio') {
                   12236:             $output .= '<p>'.&mt('or').'</p>';
                   12237:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12238:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12239:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12240:             $returnflag = 'modify_orightml';
                   12241:         }
                   12242:     }
1.1071    raeburn  12243:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12244: }
                   12245: 
                   12246: sub modify_html_form {
                   12247:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12248:     my $end = 0;
                   12249:     my $modifyform;
                   12250:     if ($context eq 'upload_embedded') {
                   12251:         return unless (ref($pathchange) eq 'HASH');
                   12252:         if ($env{'form.number_embedded_items'}) {
                   12253:             $end += $env{'form.number_embedded_items'};
                   12254:         }
                   12255:         if ($env{'form.number_pathchange_items'}) {
                   12256:             $end += $env{'form.number_pathchange_items'};
                   12257:         }
                   12258:         if ($end) {
                   12259:             for (my $i=0; $i<$end; $i++) {
                   12260:                 if ($i < $env{'form.number_embedded_items'}) {
                   12261:                     next unless($pathchange->{$i});
                   12262:                 }
                   12263:                 $modifyform .=
                   12264:                     &start_data_table_row().
                   12265:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12266:                     'checked="checked" /></td>'.
                   12267:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12268:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12269:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12270:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12271:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12272:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12273:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12274:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12275:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12276:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12277:                     &end_data_table_row();
1.1071    raeburn  12278:             }
1.987     raeburn  12279:         }
                   12280:     } else {
                   12281:         $modifyform = $pathchgtable;
                   12282:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12283:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12284:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12285:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12286:         }
                   12287:     }
                   12288:     if ($modifyform) {
1.1071    raeburn  12289:         if ($actionurl eq '/adm/dependencies') {
                   12290:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12291:         }
1.987     raeburn  12292:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12293:                '<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".
                   12294:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12295:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12296:                '</ol></p>'."\n".'<p>'.
                   12297:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12298:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12299:                &start_data_table()."\n".
                   12300:                &start_data_table_header_row().
                   12301:                '<th>'.&mt('Change?').'</th>'.
                   12302:                '<th>'.&mt('Current reference').'</th>'.
                   12303:                '<th>'.&mt('Required reference').'</th>'.
                   12304:                &end_data_table_header_row()."\n".
                   12305:                $modifyform.
                   12306:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12307:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12308:                '</form>'."\n";
                   12309:     }
                   12310:     return;
                   12311: }
                   12312: 
                   12313: sub modify_html_refs {
1.1123    raeburn  12314:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12315:     my $container;
                   12316:     if ($context eq 'portfolio') {
                   12317:         $container = $env{'form.container'};
                   12318:     } elsif ($context eq 'coursedoc') {
                   12319:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12320:     } elsif ($context eq 'manage_dependencies') {
                   12321:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12322:         $container = "/$container";
1.1123    raeburn  12323:     } elsif ($context eq 'syllabus') {
                   12324:         $container = $url;
1.987     raeburn  12325:     } else {
1.1027    raeburn  12326:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12327:     }
                   12328:     my (%allfiles,%codebase,$output,$content);
                   12329:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12330:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12331:         if (wantarray) {
                   12332:             return ('',0,0); 
                   12333:         } else {
                   12334:             return;
                   12335:         }
                   12336:     }
                   12337:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12338:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12339:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12340:             if (wantarray) {
                   12341:                 return ('',0,0);
                   12342:             } else {
                   12343:                 return;
                   12344:             }
                   12345:         } 
1.987     raeburn  12346:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12347:         if ($content eq '-1') {
                   12348:             if (wantarray) {
                   12349:                 return ('',0,0);
                   12350:             } else {
                   12351:                 return;
                   12352:             }
                   12353:         }
1.987     raeburn  12354:     } else {
1.1071    raeburn  12355:         unless ($container =~ /^\Q$dir_root\E/) {
                   12356:             if (wantarray) {
                   12357:                 return ('',0,0);
                   12358:             } else {
                   12359:                 return;
                   12360:             }
                   12361:         } 
1.1317    raeburn  12362:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12363:             $content = join('', <$fh>);
                   12364:             close($fh);
                   12365:         } else {
1.1071    raeburn  12366:             if (wantarray) {
                   12367:                 return ('',0,0);
                   12368:             } else {
                   12369:                 return;
                   12370:             }
1.987     raeburn  12371:         }
                   12372:     }
                   12373:     my ($count,$codebasecount) = (0,0);
                   12374:     my $mm = new File::MMagic;
                   12375:     my $mime_type = $mm->checktype_contents($content);
                   12376:     if ($mime_type eq 'text/html') {
                   12377:         my $parse_result = 
                   12378:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12379:                                                     \%codebase,\$content);
                   12380:         if ($parse_result eq 'ok') {
                   12381:             foreach my $i (@changes) {
                   12382:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12383:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12384:                 if ($allfiles{$ref}) {
                   12385:                     my $newname =  $orig;
                   12386:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12387:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12388:                     if ($attrib_regexp =~ /:/) {
                   12389:                         $attrib_regexp =~ s/\:/|/g;
                   12390:                     }
                   12391:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12392:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12393:                         $count += $numchg;
1.1123    raeburn  12394:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12395:                         delete($allfiles{$ref});
1.987     raeburn  12396:                     }
                   12397:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12398:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12399:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12400:                         $codebasecount ++;
                   12401:                     }
                   12402:                 }
                   12403:             }
1.1123    raeburn  12404:             my $skiprewrites;
1.987     raeburn  12405:             if ($count || $codebasecount) {
                   12406:                 my $saveresult;
1.1071    raeburn  12407:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12408:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12409:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12410:                     if ($url eq $container) {
                   12411:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12412:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12413:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12414:                                             $fname.'</span>').'</p>';
1.987     raeburn  12415:                     } else {
                   12416:                          $output = '<p class="LC_error">'.
                   12417:                                    &mt('Error: update failed for: [_1].',
                   12418:                                    '<span class="LC_filename">'.
                   12419:                                    $container.'</span>').'</p>';
                   12420:                     }
1.1123    raeburn  12421:                     if ($context eq 'syllabus') {
                   12422:                         unless ($saveresult eq 'ok') {
                   12423:                             $skiprewrites = 1;
                   12424:                         }
                   12425:                     }
1.987     raeburn  12426:                 } else {
1.1317    raeburn  12427:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12428:                         print $fh $content;
                   12429:                         close($fh);
                   12430:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12431:                                   $count,'<span class="LC_filename">'.
                   12432:                                   $container.'</span>').'</p>';
1.661     raeburn  12433:                     } else {
1.987     raeburn  12434:                          $output = '<p class="LC_error">'.
                   12435:                                    &mt('Error: could not update [_1].',
                   12436:                                    '<span class="LC_filename">'.
                   12437:                                    $container.'</span>').'</p>';
1.661     raeburn  12438:                     }
                   12439:                 }
                   12440:             }
1.1123    raeburn  12441:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12442:                 my ($actionurl,$state);
                   12443:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12444:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12445:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12446:                                               \%codebase,
                   12447:                                               {'context' => 'rewrites',
                   12448:                                                'ignore_remote_references' => 1,});
                   12449:                 if (ref($mapping) eq 'HASH') {
                   12450:                     my $rewrites = 0;
                   12451:                     foreach my $key (keys(%{$mapping})) {
                   12452:                         next if ($key =~ m{^https?://});
                   12453:                         my $ref = $mapping->{$key};
                   12454:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12455:                         my $attrib;
                   12456:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12457:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12458:                         }
                   12459:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12460:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12461:                             $rewrites += $numchg;
                   12462:                         }
                   12463:                     }
                   12464:                     if ($rewrites) {
                   12465:                         my $saveresult; 
                   12466:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12467:                         if ($url eq $container) {
                   12468:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12469:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12470:                                             $count,'<span class="LC_filename">'.
                   12471:                                             $fname.'</span>').'</p>';
                   12472:                         } else {
                   12473:                             $output .= '<p class="LC_error">'.
                   12474:                                        &mt('Error: could not update links in [_1].',
                   12475:                                        '<span class="LC_filename">'.
                   12476:                                        $container.'</span>').'</p>';
                   12477: 
                   12478:                         }
                   12479:                     }
                   12480:                 }
                   12481:             }
1.987     raeburn  12482:         } else {
                   12483:             &logthis('Failed to parse '.$container.
                   12484:                      ' to modify references: '.$parse_result);
1.661     raeburn  12485:         }
                   12486:     }
1.1071    raeburn  12487:     if (wantarray) {
                   12488:         return ($output,$count,$codebasecount);
                   12489:     } else {
                   12490:         return $output;
                   12491:     }
1.661     raeburn  12492: }
                   12493: 
                   12494: sub check_for_existing {
                   12495:     my ($path,$fname,$element) = @_;
                   12496:     my ($state,$msg);
                   12497:     if (-d $path.'/'.$fname) {
                   12498:         $state = 'exists';
                   12499:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12500:     } elsif (-e $path.'/'.$fname) {
                   12501:         $state = 'exists';
                   12502:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12503:     }
                   12504:     if ($state eq 'exists') {
                   12505:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12506:     }
                   12507:     return ($state,$msg);
                   12508: }
                   12509: 
                   12510: sub check_for_upload {
                   12511:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12512:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12513:     my $filesize = length($env{'form.'.$element});
                   12514:     if (!$filesize) {
                   12515:         my $msg = '<span class="LC_error">'.
                   12516:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12517:                       '<span class="LC_filename">'.$fname.'</span>',
                   12518:                       $filesize).'<br />'.
1.1007    raeburn  12519:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12520:                   '</span>';
                   12521:         return ('zero_bytes',$msg);
                   12522:     }
                   12523:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12524:     my $getpropath = 1;
1.1021    raeburn  12525:     my ($dirlistref,$listerror) =
                   12526:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12527:     my $found_file = 0;
                   12528:     my $locked_file = 0;
1.991     raeburn  12529:     my @lockers;
                   12530:     my $navmap;
                   12531:     if ($env{'request.course.id'}) {
                   12532:         $navmap = Apache::lonnavmaps::navmap->new();
                   12533:     }
1.1021    raeburn  12534:     if (ref($dirlistref) eq 'ARRAY') {
                   12535:         foreach my $line (@{$dirlistref}) {
                   12536:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12537:             if ($file_name eq $fname){
                   12538:                 $file_name = $path.$file_name;
                   12539:                 if ($group ne '') {
                   12540:                     $file_name = $group.$file_name;
                   12541:                 }
                   12542:                 $found_file = 1;
                   12543:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12544:                     foreach my $lock (@lockers) {
                   12545:                         if (ref($lock) eq 'ARRAY') {
                   12546:                             my ($symb,$crsid) = @{$lock};
                   12547:                             if ($crsid eq $env{'request.course.id'}) {
                   12548:                                 if (ref($navmap)) {
                   12549:                                     my $res = $navmap->getBySymb($symb);
                   12550:                                     foreach my $part (@{$res->parts()}) { 
                   12551:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12552:                                         unless (($slot_status == $res->RESERVED) ||
                   12553:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12554:                                             $locked_file = 1;
                   12555:                                         }
1.991     raeburn  12556:                                     }
1.1021    raeburn  12557:                                 } else {
                   12558:                                     $locked_file = 1;
1.991     raeburn  12559:                                 }
                   12560:                             } else {
                   12561:                                 $locked_file = 1;
                   12562:                             }
                   12563:                         }
1.1021    raeburn  12564:                    }
                   12565:                 } else {
                   12566:                     my @info = split(/\&/,$rest);
                   12567:                     my $currsize = $info[6]/1000;
                   12568:                     if ($currsize < $filesize) {
                   12569:                         my $extra = $filesize - $currsize;
                   12570:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12571:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12572:                                       &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   12573:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12574:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12575:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12576:                             return ('will_exceed_quota',$msg);
                   12577:                         }
1.984     raeburn  12578:                     }
                   12579:                 }
1.661     raeburn  12580:             }
                   12581:         }
                   12582:     }
                   12583:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12584:         my $msg = '<p class="LC_warning">'.
                   12585:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12586:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12587:         return ('will_exceed_quota',$msg);
                   12588:     } elsif ($found_file) {
                   12589:         if ($locked_file) {
1.1179    bisitz   12590:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12591:             $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   12592:             $msg .= '</p>';
1.661     raeburn  12593:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12594:             return ('file_locked',$msg);
                   12595:         } else {
1.1179    bisitz   12596:             my $msg = '<p class="LC_error">';
1.984     raeburn  12597:             $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   12598:             $msg .= '</p>';
1.984     raeburn  12599:             return ('existingfile',$msg);
1.661     raeburn  12600:         }
                   12601:     }
                   12602: }
                   12603: 
1.987     raeburn  12604: sub check_for_traversal {
                   12605:     my ($path,$url,$toplevel) = @_;
                   12606:     my @parts=split(/\//,$path);
                   12607:     my $cleanpath;
                   12608:     my $fullpath = $url;
                   12609:     for (my $i=0;$i<@parts;$i++) {
                   12610:         next if ($parts[$i] eq '.');
                   12611:         if ($parts[$i] eq '..') {
                   12612:             $fullpath =~ s{([^/]+/)$}{};
                   12613:         } else {
                   12614:             $fullpath .= $parts[$i].'/';
                   12615:         }
                   12616:     }
                   12617:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12618:         $cleanpath = $1;
                   12619:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12620:         my $curr_toprel = $1;
                   12621:         my @parts = split(/\//,$curr_toprel);
                   12622:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12623:         my @urlparts = split(/\//,$url_toprel);
                   12624:         my $doubledots;
                   12625:         my $startdiff = -1;
                   12626:         for (my $i=0; $i<@urlparts; $i++) {
                   12627:             if ($startdiff == -1) {
                   12628:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12629:                     $startdiff = $i;
                   12630:                     $doubledots .= '../';
                   12631:                 }
                   12632:             } else {
                   12633:                 $doubledots .= '../';
                   12634:             }
                   12635:         }
                   12636:         if ($startdiff > -1) {
                   12637:             $cleanpath = $doubledots;
                   12638:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12639:                 $cleanpath .= $parts[$i].'/';
                   12640:             }
                   12641:         }
                   12642:     }
                   12643:     $cleanpath =~ s{(/)$}{};
                   12644:     return $cleanpath;
                   12645: }
1.31      albertel 12646: 
1.1053    raeburn  12647: sub is_archive_file {
                   12648:     my ($mimetype) = @_;
                   12649:     if (($mimetype eq 'application/octet-stream') ||
                   12650:         ($mimetype eq 'application/x-stuffit') ||
                   12651:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12652:         return 1;
                   12653:     }
                   12654:     return;
                   12655: }
                   12656: 
                   12657: sub decompress_form {
1.1065    raeburn  12658:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12659:     my %lt = &Apache::lonlocal::texthash (
                   12660:         this => 'This file is an archive file.',
1.1067    raeburn  12661:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12662:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12663:         youm => 'You may wish to extract its contents.',
                   12664:         extr => 'Extract contents',
1.1067    raeburn  12665:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12666:         proa => 'Process automatically?',
1.1053    raeburn  12667:         yes  => 'Yes',
                   12668:         no   => 'No',
1.1067    raeburn  12669:         fold => 'Title for folder containing movie',
                   12670:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12671:     );
1.1065    raeburn  12672:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12673:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12674:     my $info = &list_archive_contents($fileloc,\@paths);
                   12675:     if (@paths) {
                   12676:         foreach my $path (@paths) {
                   12677:             $path =~ s{^/}{};
1.1067    raeburn  12678:             if ($path =~ m{^([^/]+)/$}) {
                   12679:                 $topdir = $1;
                   12680:             }
1.1065    raeburn  12681:             if ($path =~ m{^([^/]+)/}) {
                   12682:                 $toplevel{$1} = $path;
                   12683:             } else {
                   12684:                 $toplevel{$path} = $path;
                   12685:             }
                   12686:         }
                   12687:     }
1.1067    raeburn  12688:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12689:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12690:                         "$topdir/media/",
                   12691:                         "$topdir/media/$topdir.mp4",
                   12692:                         "$topdir/media/FirstFrame.png",
                   12693:                         "$topdir/media/player.swf",
                   12694:                         "$topdir/media/swfobject.js",
                   12695:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12696:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12697:                          "$topdir/$topdir.mp4",
                   12698:                          "$topdir/$topdir\_config.xml",
                   12699:                          "$topdir/$topdir\_controller.swf",
                   12700:                          "$topdir/$topdir\_embed.css",
                   12701:                          "$topdir/$topdir\_First_Frame.png",
                   12702:                          "$topdir/$topdir\_player.html",
                   12703:                          "$topdir/$topdir\_Thumbnails.png",
                   12704:                          "$topdir/playerProductInstall.swf",
                   12705:                          "$topdir/scripts/",
                   12706:                          "$topdir/scripts/config_xml.js",
                   12707:                          "$topdir/scripts/handlebars.js",
                   12708:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12709:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12710:                          "$topdir/scripts/modernizr.js",
                   12711:                          "$topdir/scripts/player-min.js",
                   12712:                          "$topdir/scripts/swfobject.js",
                   12713:                          "$topdir/skins/",
                   12714:                          "$topdir/skins/configuration_express.xml",
                   12715:                          "$topdir/skins/express_show/",
                   12716:                          "$topdir/skins/express_show/player-min.css",
                   12717:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12718:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12719:                          "$topdir/$topdir.mp4",
                   12720:                          "$topdir/$topdir\_config.xml",
                   12721:                          "$topdir/$topdir\_controller.swf",
                   12722:                          "$topdir/$topdir\_embed.css",
                   12723:                          "$topdir/$topdir\_First_Frame.png",
                   12724:                          "$topdir/$topdir\_player.html",
                   12725:                          "$topdir/$topdir\_Thumbnails.png",
                   12726:                          "$topdir/playerProductInstall.swf",
                   12727:                          "$topdir/scripts/",
                   12728:                          "$topdir/scripts/config_xml.js",
                   12729:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12730:                          "$topdir/skins/",
                   12731:                          "$topdir/skins/configuration_express.xml",
                   12732:                          "$topdir/skins/express_show/",
                   12733:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12734:                          "$topdir/skins/express_show/spritesheet.png",
                   12735:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12736:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12737:         if (@diffs == 0) {
1.1164    raeburn  12738:             $is_camtasia = 6;
                   12739:         } else {
1.1197    raeburn  12740:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12741:             if (@diffs == 0) {
                   12742:                 $is_camtasia = 8;
1.1197    raeburn  12743:             } else {
                   12744:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12745:                 if (@diffs == 0) {
                   12746:                     $is_camtasia = 8;
                   12747:                 }
1.1164    raeburn  12748:             }
1.1067    raeburn  12749:         }
                   12750:     }
                   12751:     my $output;
                   12752:     if ($is_camtasia) {
                   12753:         $output = <<"ENDCAM";
                   12754: <script type="text/javascript" language="Javascript">
                   12755: // <![CDATA[
                   12756: 
                   12757: function camtasiaToggle() {
                   12758:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12759:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12760:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12761:                 document.getElementById('camtasia_titles').style.display='block';
                   12762:             } else {
                   12763:                 document.getElementById('camtasia_titles').style.display='none';
                   12764:             }
                   12765:         }
                   12766:     }
                   12767:     return;
                   12768: }
                   12769: 
                   12770: // ]]>
                   12771: </script>
                   12772: <p>$lt{'camt'}</p>
                   12773: ENDCAM
1.1065    raeburn  12774:     } else {
1.1067    raeburn  12775:         $output = '<p>'.$lt{'this'};
                   12776:         if ($info eq '') {
                   12777:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12778:         } else {
                   12779:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12780:                        '<div><pre>'.$info.'</pre></div>';
                   12781:         }
1.1065    raeburn  12782:     }
1.1067    raeburn  12783:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12784:     my $duplicates;
                   12785:     my $num = 0;
                   12786:     if (ref($dirlist) eq 'ARRAY') {
                   12787:         foreach my $item (@{$dirlist}) {
                   12788:             if (ref($item) eq 'ARRAY') {
                   12789:                 if (exists($toplevel{$item->[0]})) {
                   12790:                     $duplicates .= 
                   12791:                         &start_data_table_row().
                   12792:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12793:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12794:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12795:                         'value="1" />'.&mt('Yes').'</label>'.
                   12796:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12797:                         '<td>'.$item->[0].'</td>';
                   12798:                     if ($item->[2]) {
                   12799:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12800:                     } else {
                   12801:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12802:                     }
                   12803:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12804:                                    '<td>'.
                   12805:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12806:                                    '</td>'.
                   12807:                                    &end_data_table_row();
                   12808:                     $num ++;
                   12809:                 }
                   12810:             }
                   12811:         }
                   12812:     }
                   12813:     my $itemcount;
                   12814:     if (@paths > 0) {
                   12815:         $itemcount = scalar(@paths);
                   12816:     } else {
                   12817:         $itemcount = 1;
                   12818:     }
1.1067    raeburn  12819:     if ($is_camtasia) {
                   12820:         $output .= $lt{'auto'}.'<br />'.
                   12821:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12822:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12823:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12824:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12825:                    $lt{'no'}.'</label></span><br />'.
                   12826:                    '<div id="camtasia_titles" style="display:block">'.
                   12827:                    &Apache::lonhtmlcommon::start_pick_box().
                   12828:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12829:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12830:                    &Apache::lonhtmlcommon::row_closure().
                   12831:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12832:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12833:                    &Apache::lonhtmlcommon::row_closure(1).
                   12834:                    &Apache::lonhtmlcommon::end_pick_box().
                   12835:                    '</div>';
                   12836:     }
1.1065    raeburn  12837:     $output .= 
                   12838:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12839:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12840:         "\n";
1.1065    raeburn  12841:     if ($duplicates ne '') {
                   12842:         $output .= '<p><span class="LC_warning">'.
                   12843:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12844:                    &start_data_table().
                   12845:                    &start_data_table_header_row().
                   12846:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12847:                    '<th>'.&mt('Name').'</th>'.
                   12848:                    '<th>'.&mt('Type').'</th>'.
                   12849:                    '<th>'.&mt('Size').'</th>'.
                   12850:                    '<th>'.&mt('Last modified').'</th>'.
                   12851:                    &end_data_table_header_row().
                   12852:                    $duplicates.
                   12853:                    &end_data_table().
                   12854:                    '</p>';
                   12855:     }
1.1067    raeburn  12856:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12857:     if (ref($hiddenelements) eq 'HASH') {
                   12858:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12859:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12860:         }
                   12861:     }
                   12862:     $output .= <<"END";
1.1067    raeburn  12863: <br />
1.1053    raeburn  12864: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12865: </form>
                   12866: $noextract
                   12867: END
                   12868:     return $output;
                   12869: }
                   12870: 
1.1065    raeburn  12871: sub decompression_utility {
                   12872:     my ($program) = @_;
                   12873:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12874:     my $location;
                   12875:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12876:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12877:                          '/usr/sbin/') {
                   12878:             if (-x $dir.$program) {
                   12879:                 $location = $dir.$program;
                   12880:                 last;
                   12881:             }
                   12882:         }
                   12883:     }
                   12884:     return $location;
                   12885: }
                   12886: 
                   12887: sub list_archive_contents {
                   12888:     my ($file,$pathsref) = @_;
                   12889:     my (@cmd,$output);
                   12890:     my $needsregexp;
                   12891:     if ($file =~ /\.zip$/) {
                   12892:         @cmd = (&decompression_utility('unzip'),"-l");
                   12893:         $needsregexp = 1;
                   12894:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12895:              ($file =~ /\.tgz$/)) {
                   12896:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12897:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12898:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12899:     } elsif ($file =~ m|\.tar$|) {
                   12900:         @cmd = (&decompression_utility('tar'),"-tf");
                   12901:     }
                   12902:     if (@cmd) {
                   12903:         undef($!);
                   12904:         undef($@);
                   12905:         if (open(my $fh,"-|", @cmd, $file)) {
                   12906:             while (my $line = <$fh>) {
                   12907:                 $output .= $line;
                   12908:                 chomp($line);
                   12909:                 my $item;
                   12910:                 if ($needsregexp) {
                   12911:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12912:                 } else {
                   12913:                     $item = $line;
                   12914:                 }
                   12915:                 if ($item ne '') {
                   12916:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12917:                         push(@{$pathsref},$item);
                   12918:                     } 
                   12919:                 }
                   12920:             }
                   12921:             close($fh);
                   12922:         }
                   12923:     }
                   12924:     return $output;
                   12925: }
                   12926: 
1.1053    raeburn  12927: sub decompress_uploaded_file {
                   12928:     my ($file,$dir) = @_;
                   12929:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12930:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12931:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12932:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12933:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12934:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12935:     my $decompressed = $env{'cgi.decompressed'};
                   12936:     &Apache::lonnet::delenv('cgi.file');
                   12937:     &Apache::lonnet::delenv('cgi.dir');
                   12938:     &Apache::lonnet::delenv('cgi.decompressed');
                   12939:     return ($decompressed,$result);
                   12940: }
                   12941: 
1.1055    raeburn  12942: sub process_decompression {
                   12943:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  12944:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12945:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12946:                &mt('Unexpected file path.').'</p>'."\n";
                   12947:     }
                   12948:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12949:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12950:                &mt('Unexpected course context.').'</p>'."\n";
                   12951:     }
1.1293    raeburn  12952:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  12953:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12954:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12955:     }
1.1055    raeburn  12956:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12957:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12958:         $error = &mt('Filename not a supported archive file type.').
                   12959:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12960:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12961:     } else {
                   12962:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12963:         if ($docuhome eq 'no_host') {
                   12964:             $error = &mt('Could not determine home server for course.');
                   12965:         } else {
                   12966:             my @ids=&Apache::lonnet::current_machine_ids();
                   12967:             my $currdir = "$dir_root/$destination";
                   12968:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12969:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12970:                        "$dir_root/$destination";
                   12971:             } else {
                   12972:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12973:                        "$dir_root/$docudom/$docuname/$destination";
                   12974:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12975:                     $error = &mt('Archive file not found.');
                   12976:                 }
                   12977:             }
1.1065    raeburn  12978:             my (@to_overwrite,@to_skip);
                   12979:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12980:                 my $total = $env{'form.archive_overwrite_total'};
                   12981:                 for (my $i=0; $i<$total; $i++) {
                   12982:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12983:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12984:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12985:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12986:                     }
                   12987:                 }
                   12988:             }
                   12989:             my $numskip = scalar(@to_skip);
1.1292    raeburn  12990:             my $numoverwrite = scalar(@to_overwrite);
                   12991:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  12992:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12993:             } elsif ($dir eq '') {
1.1055    raeburn  12994:                 $error = &mt('Directory containing archive file unavailable.');
                   12995:             } elsif (!$error) {
1.1065    raeburn  12996:                 my ($decompressed,$display);
1.1292    raeburn  12997:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12998:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12999:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13000:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13001:                         ($decompressed,$display) = 
                   13002:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13003:                         foreach my $item (@to_skip) {
                   13004:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13005:                                 if (-f "$dir/$tempdir/$item") { 
                   13006:                                     unlink("$dir/$tempdir/$item");
                   13007:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13008:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13009:                                 }
                   13010:                             }
                   13011:                         }
                   13012:                         foreach my $item (@to_overwrite) {
                   13013:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13014:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13015:                                     if (-f "$dir/$item") {
                   13016:                                         unlink("$dir/$item");
                   13017:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13018:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13019:                                     }
                   13020:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13021:                                 }
1.1065    raeburn  13022:                             }
                   13023:                         }
1.1292    raeburn  13024:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13025:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13026:                         }
1.1065    raeburn  13027:                     }
                   13028:                 } else {
                   13029:                     ($decompressed,$display) = 
                   13030:                         &decompress_uploaded_file($file,$dir);
                   13031:                 }
1.1055    raeburn  13032:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13033:                     $output = '<p class="LC_info">'.
                   13034:                               &mt('Files extracted successfully from archive.').
                   13035:                               '</p>'."\n";
1.1055    raeburn  13036:                     my ($warning,$result,@contents);
                   13037:                     my ($newdirlistref,$newlisterror) =
                   13038:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13039:                                                  $docuname,1);
                   13040:                     my (%is_dir,%changes,@newitems);
                   13041:                     my $dirptr = 16384;
1.1065    raeburn  13042:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13043:                         foreach my $dir_line (@{$newdirlistref}) {
                   13044:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13045:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13046:                                 push(@newitems,$item);
                   13047:                                 if ($dirptr&$testdir) {
                   13048:                                     $is_dir{$item} = 1;
                   13049:                                 }
                   13050:                                 $changes{$item} = 1;
                   13051:                             }
                   13052:                         }
                   13053:                     }
                   13054:                     if (keys(%changes) > 0) {
                   13055:                         foreach my $item (sort(@newitems)) {
                   13056:                             if ($changes{$item}) {
                   13057:                                 push(@contents,$item);
                   13058:                             }
                   13059:                         }
                   13060:                     }
                   13061:                     if (@contents > 0) {
1.1067    raeburn  13062:                         my $wantform;
                   13063:                         unless ($env{'form.autoextract_camtasia'}) {
                   13064:                             $wantform = 1;
                   13065:                         }
1.1056    raeburn  13066:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13067:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13068:                                                                 $currdir,\%is_dir,
                   13069:                                                                 \%children,\%parent,
1.1056    raeburn  13070:                                                                 \@contents,\%dirorder,
                   13071:                                                                 \%titles,$wantform);
1.1055    raeburn  13072:                         if ($datatable ne '') {
                   13073:                             $output .= &archive_options_form('decompressed',$datatable,
                   13074:                                                              $count,$hiddenelem);
1.1065    raeburn  13075:                             my $startcount = 6;
1.1055    raeburn  13076:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13077:                                                            \%titles,\%children);
1.1055    raeburn  13078:                         }
1.1067    raeburn  13079:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13080:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13081:                             my %displayed;
                   13082:                             my $total = 1;
                   13083:                             $env{'form.archive_directory'} = [];
                   13084:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13085:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13086:                                 $path =~ s{/$}{};
                   13087:                                 my $item;
                   13088:                                 if ($path ne '') {
                   13089:                                     $item = "$path/$titles{$i}";
                   13090:                                 } else {
                   13091:                                     $item = $titles{$i};
                   13092:                                 }
                   13093:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13094:                                 if ($item eq $contents[0]) {
                   13095:                                     push(@{$env{'form.archive_directory'}},$i);
                   13096:                                     $env{'form.archive_'.$i} = 'display';
                   13097:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13098:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13099:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13100:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13101:                                     $env{'form.archive_'.$i} = 'display';
                   13102:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13103:                                     $displayed{'web'} = $i;
                   13104:                                 } else {
1.1164    raeburn  13105:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13106:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13107:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13108:                                         push(@{$env{'form.archive_directory'}},$i);
                   13109:                                     }
                   13110:                                     $env{'form.archive_'.$i} = 'dependency';
                   13111:                                 }
                   13112:                                 $total ++;
                   13113:                             }
                   13114:                             for (my $i=1; $i<$total; $i++) {
                   13115:                                 next if ($i == $displayed{'web'});
                   13116:                                 next if ($i == $displayed{'folder'});
                   13117:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13118:                             }
                   13119:                             $env{'form.phase'} = 'decompress_cleanup';
                   13120:                             $env{'form.archivedelete'} = 1;
                   13121:                             $env{'form.archive_count'} = $total-1;
                   13122:                             $output .=
                   13123:                                 &process_extracted_files('coursedocs',$docudom,
                   13124:                                                          $docuname,$destination,
                   13125:                                                          $dir_root,$hiddenelem);
                   13126:                         }
1.1055    raeburn  13127:                     } else {
                   13128:                         $warning = &mt('No new items extracted from archive file.');
                   13129:                     }
                   13130:                 } else {
                   13131:                     $output = $display;
                   13132:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13133:                 }
                   13134:             }
                   13135:         }
                   13136:     }
                   13137:     if ($error) {
                   13138:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13139:                    $error.'</p>'."\n";
                   13140:     }
                   13141:     if ($warning) {
                   13142:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13143:     }
                   13144:     return $output;
                   13145: }
                   13146: 
                   13147: sub get_extracted {
1.1056    raeburn  13148:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13149:         $titles,$wantform) = @_;
1.1055    raeburn  13150:     my $count = 0;
                   13151:     my $depth = 0;
                   13152:     my $datatable;
1.1056    raeburn  13153:     my @hierarchy;
1.1055    raeburn  13154:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13155:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13156:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13157:     foreach my $item (@{$contents}) {
                   13158:         $count ++;
1.1056    raeburn  13159:         @{$dirorder->{$count}} = @hierarchy;
                   13160:         $titles->{$count} = $item;
1.1055    raeburn  13161:         &archive_hierarchy($depth,$count,$parent,$children);
                   13162:         if ($wantform) {
                   13163:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13164:                                        $currdir,$depth,$count);
                   13165:         }
                   13166:         if ($is_dir->{$item}) {
                   13167:             $depth ++;
1.1056    raeburn  13168:             push(@hierarchy,$count);
                   13169:             $parent->{$depth} = $count;
1.1055    raeburn  13170:             $datatable .=
                   13171:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13172:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13173:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13174:             $depth --;
1.1056    raeburn  13175:             pop(@hierarchy);
1.1055    raeburn  13176:         }
                   13177:     }
                   13178:     return ($count,$datatable);
                   13179: }
                   13180: 
                   13181: sub recurse_extracted_archive {
1.1056    raeburn  13182:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13183:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13184:     my $result='';
1.1056    raeburn  13185:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13186:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13187:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13188:         return $result;
                   13189:     }
                   13190:     my $dirptr = 16384;
                   13191:     my ($newdirlistref,$newlisterror) =
                   13192:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13193:     if (ref($newdirlistref) eq 'ARRAY') {
                   13194:         foreach my $dir_line (@{$newdirlistref}) {
                   13195:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13196:             unless ($item =~ /^\.+$/) {
                   13197:                 $$count ++;
1.1056    raeburn  13198:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13199:                 $titles->{$$count} = $item;
1.1055    raeburn  13200:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13201: 
1.1055    raeburn  13202:                 my $is_dir;
                   13203:                 if ($dirptr&$testdir) {
                   13204:                     $is_dir = 1;
                   13205:                 }
                   13206:                 if ($wantform) {
                   13207:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13208:                 }
                   13209:                 if ($is_dir) {
                   13210:                     $$depth ++;
1.1056    raeburn  13211:                     push(@{$hierarchy},$$count);
                   13212:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13213:                     $result .=
                   13214:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13215:                                                    $docuname,$depth,$count,
1.1056    raeburn  13216:                                                    $hierarchy,$dirorder,$children,
                   13217:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13218:                     $$depth --;
1.1056    raeburn  13219:                     pop(@{$hierarchy});
1.1055    raeburn  13220:                 }
                   13221:             }
                   13222:         }
                   13223:     }
                   13224:     return $result;
                   13225: }
                   13226: 
                   13227: sub archive_hierarchy {
                   13228:     my ($depth,$count,$parent,$children) =@_;
                   13229:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13230:         if (exists($parent->{$depth})) {
                   13231:              $children->{$parent->{$depth}} .= $count.':';
                   13232:         }
                   13233:     }
                   13234:     return;
                   13235: }
                   13236: 
                   13237: sub archive_row {
                   13238:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13239:     my ($name) = ($item =~ m{([^/]+)$});
                   13240:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13241:                                        'display'    => 'Add as file',
1.1055    raeburn  13242:                                        'dependency' => 'Include as dependency',
                   13243:                                        'discard'    => 'Discard',
                   13244:                                       );
                   13245:     if ($is_dir) {
1.1059    raeburn  13246:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13247:     }
1.1056    raeburn  13248:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13249:     my $offset = 0;
1.1055    raeburn  13250:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13251:         $offset ++;
1.1065    raeburn  13252:         if ($action ne 'display') {
                   13253:             $offset ++;
                   13254:         }  
1.1055    raeburn  13255:         $output .= '<td><span class="LC_nobreak">'.
                   13256:                    '<label><input type="radio" name="archive_'.$count.
                   13257:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13258:         my $text = $choices{$action};
                   13259:         if ($is_dir) {
                   13260:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13261:             if ($action eq 'display') {
1.1059    raeburn  13262:                 $text = &mt('Add as folder');
1.1055    raeburn  13263:             }
1.1056    raeburn  13264:         } else {
                   13265:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13266: 
                   13267:         }
                   13268:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13269:         if ($action eq 'dependency') {
                   13270:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13271:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13272:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13273:                        '<option value=""></option>'."\n".
                   13274:                        '</select>'."\n".
                   13275:                        '</div>';
1.1059    raeburn  13276:         } elsif ($action eq 'display') {
                   13277:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13278:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13279:                        '</div>';
1.1055    raeburn  13280:         }
1.1056    raeburn  13281:         $output .= '</td>';
1.1055    raeburn  13282:     }
                   13283:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13284:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13285:     for (my $i=0; $i<$depth; $i++) {
                   13286:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13287:     }
                   13288:     if ($is_dir) {
                   13289:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13290:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13291:     } else {
                   13292:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13293:     }
                   13294:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13295:                &end_data_table_row();
                   13296:     return $output;
                   13297: }
                   13298: 
                   13299: sub archive_options_form {
1.1065    raeburn  13300:     my ($form,$display,$count,$hiddenelem) = @_;
                   13301:     my %lt = &Apache::lonlocal::texthash(
                   13302:                perm => 'Permanently remove archive file?',
                   13303:                hows => 'How should each extracted item be incorporated in the course?',
                   13304:                cont => 'Content actions for all',
                   13305:                addf => 'Add as folder/file',
                   13306:                incd => 'Include as dependency for a displayed file',
                   13307:                disc => 'Discard',
                   13308:                no   => 'No',
                   13309:                yes  => 'Yes',
                   13310:                save => 'Save',
                   13311:     );
                   13312:     my $output = <<"END";
                   13313: <form name="$form" method="post" action="">
                   13314: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13315: <label>
                   13316:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13317: </label>
                   13318: &nbsp;
                   13319: <label>
                   13320:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13321: </span>
                   13322: </p>
                   13323: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13324: <br />$lt{'hows'}
                   13325: <div class="LC_columnSection">
                   13326:   <fieldset>
                   13327:     <legend>$lt{'cont'}</legend>
                   13328:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13329:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13330:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13331:   </fieldset>
                   13332: </div>
                   13333: END
                   13334:     return $output.
1.1055    raeburn  13335:            &start_data_table()."\n".
1.1065    raeburn  13336:            $display."\n".
1.1055    raeburn  13337:            &end_data_table()."\n".
                   13338:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13339:            $hiddenelem.
1.1065    raeburn  13340:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13341:            '</form>';
                   13342: }
                   13343: 
                   13344: sub archive_javascript {
1.1056    raeburn  13345:     my ($startcount,$numitems,$titles,$children) = @_;
                   13346:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13347:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13348:     my $scripttag = <<START;
                   13349: <script type="text/javascript">
                   13350: // <![CDATA[
                   13351: 
                   13352: function checkAll(form,prefix) {
                   13353:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13354:     for (var i=0; i < form.elements.length; i++) {
                   13355:         var id = form.elements[i].id;
                   13356:         if ((id != '') && (id != undefined)) {
                   13357:             if (idstr.test(id)) {
                   13358:                 if (form.elements[i].type == 'radio') {
                   13359:                     form.elements[i].checked = true;
1.1056    raeburn  13360:                     var nostart = i-$startcount;
1.1059    raeburn  13361:                     var offset = nostart%7;
                   13362:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13363:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13364:                 }
                   13365:             }
                   13366:         }
                   13367:     }
                   13368: }
                   13369: 
                   13370: function propagateCheck(form,count) {
                   13371:     if (count > 0) {
1.1059    raeburn  13372:         var startelement = $startcount + ((count-1) * 7);
                   13373:         for (var j=1; j<6; j++) {
                   13374:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13375:                 var item = startelement + j; 
                   13376:                 if (form.elements[item].type == 'radio') {
                   13377:                     if (form.elements[item].checked) {
                   13378:                         containerCheck(form,count,j);
                   13379:                         break;
                   13380:                     }
1.1055    raeburn  13381:                 }
                   13382:             }
                   13383:         }
                   13384:     }
                   13385: }
                   13386: 
                   13387: numitems = $numitems
1.1056    raeburn  13388: var titles = new Array(numitems);
                   13389: var parents = new Array(numitems);
1.1055    raeburn  13390: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13391:     parents[i] = new Array;
1.1055    raeburn  13392: }
1.1059    raeburn  13393: var maintitle = '$maintitle';
1.1055    raeburn  13394: 
                   13395: START
                   13396: 
1.1056    raeburn  13397:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13398:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13399:         for (my $i=0; $i<@contents; $i ++) {
                   13400:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13401:         }
                   13402:     }
                   13403: 
1.1056    raeburn  13404:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13405:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13406:     }
                   13407: 
1.1055    raeburn  13408:     $scripttag .= <<END;
                   13409: 
                   13410: function containerCheck(form,count,offset) {
                   13411:     if (count > 0) {
1.1056    raeburn  13412:         dependencyCheck(form,count,offset);
1.1059    raeburn  13413:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13414:         form.elements[item].checked = true;
                   13415:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13416:             if (parents[count].length > 0) {
                   13417:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13418:                     containerCheck(form,parents[count][j],offset);
                   13419:                 }
                   13420:             }
                   13421:         }
                   13422:     }
                   13423: }
                   13424: 
                   13425: function dependencyCheck(form,count,offset) {
                   13426:     if (count > 0) {
1.1059    raeburn  13427:         var chosen = (offset+$startcount)+7*(count-1);
                   13428:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13429:         var currtype = form.elements[depitem].type;
                   13430:         if (form.elements[chosen].value == 'dependency') {
                   13431:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13432:             form.elements[depitem].options.length = 0;
                   13433:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13434:             for (var i=1; i<=numitems; i++) {
                   13435:                 if (i == count) {
                   13436:                     continue;
                   13437:                 }
1.1059    raeburn  13438:                 var startelement = $startcount + (i-1) * 7;
                   13439:                 for (var j=1; j<6; j++) {
                   13440:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13441:                         var item = startelement + j;
                   13442:                         if (form.elements[item].type == 'radio') {
                   13443:                             if (form.elements[item].checked) {
                   13444:                                 if (form.elements[item].value == 'display') {
                   13445:                                     var n = form.elements[depitem].options.length;
                   13446:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13447:                                 }
                   13448:                             }
                   13449:                         }
                   13450:                     }
                   13451:                 }
                   13452:             }
                   13453:         } else {
                   13454:             document.getElementById('arc_depon_'+count).style.display='none';
                   13455:             form.elements[depitem].options.length = 0;
                   13456:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13457:         }
1.1059    raeburn  13458:         titleCheck(form,count,offset);
1.1056    raeburn  13459:     }
                   13460: }
                   13461: 
                   13462: function propagateSelect(form,count,offset) {
                   13463:     if (count > 0) {
1.1065    raeburn  13464:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13465:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13466:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13467:             if (parents[count].length > 0) {
                   13468:                 for (var j=0; j<parents[count].length; j++) {
                   13469:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13470:                 }
                   13471:             }
                   13472:         }
                   13473:     }
                   13474: }
1.1056    raeburn  13475: 
                   13476: function containerSelect(form,count,offset,picked) {
                   13477:     if (count > 0) {
1.1065    raeburn  13478:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13479:         if (form.elements[item].type == 'radio') {
                   13480:             if (form.elements[item].value == 'dependency') {
                   13481:                 if (form.elements[item+1].type == 'select-one') {
                   13482:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13483:                         if (form.elements[item+1].options[i].value == picked) {
                   13484:                             form.elements[item+1].selectedIndex = i;
                   13485:                             break;
                   13486:                         }
                   13487:                     }
                   13488:                 }
                   13489:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13490:                     if (parents[count].length > 0) {
                   13491:                         for (var j=0; j<parents[count].length; j++) {
                   13492:                             containerSelect(form,parents[count][j],offset,picked);
                   13493:                         }
                   13494:                     }
                   13495:                 }
                   13496:             }
                   13497:         }
                   13498:     }
                   13499: }
                   13500: 
1.1059    raeburn  13501: function titleCheck(form,count,offset) {
                   13502:     if (count > 0) {
                   13503:         var chosen = (offset+$startcount)+7*(count-1);
                   13504:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13505:         var currtype = form.elements[depitem].type;
                   13506:         if (form.elements[chosen].value == 'display') {
                   13507:             document.getElementById('arc_title_'+count).style.display='block';
                   13508:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13509:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13510:             }
                   13511:         } else {
                   13512:             document.getElementById('arc_title_'+count).style.display='none';
                   13513:             if (currtype == 'text') { 
                   13514:                 document.getElementById('archive_title_'+count).value='';
                   13515:             }
                   13516:         }
                   13517:     }
                   13518:     return;
                   13519: }
                   13520: 
1.1055    raeburn  13521: // ]]>
                   13522: </script>
                   13523: END
                   13524:     return $scripttag;
                   13525: }
                   13526: 
                   13527: sub process_extracted_files {
1.1067    raeburn  13528:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13529:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13530:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13531:     my @ids=&Apache::lonnet::current_machine_ids();
                   13532:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13533:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13534:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13535:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13536:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13537:         $pathtocheck = "$dir_root/$destination";
                   13538:         $dir = $dir_root;
                   13539:         $ishome = 1;
                   13540:     } else {
                   13541:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13542:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13543:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13544:     }
                   13545:     my $currdir = "$dir_root/$destination";
                   13546:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13547:     if ($env{'form.folderpath'}) {
                   13548:         my @items = split('&',$env{'form.folderpath'});
                   13549:         $folders{'0'} = $items[-2];
1.1099    raeburn  13550:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13551:             $containers{'0'}='page';
                   13552:         } else {  
                   13553:             $containers{'0'}='sequence';
                   13554:         }
1.1055    raeburn  13555:     }
                   13556:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13557:     if ($numitems) {
                   13558:         for (my $i=1; $i<=$numitems; $i++) {
                   13559:             my $path = $env{'form.archive_content_'.$i};
                   13560:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13561:                 my $item = $1;
                   13562:                 $toplevelitems{$item} = $i;
                   13563:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13564:                     $is_dir{$item} = 1;
                   13565:                 }
                   13566:             }
                   13567:         }
                   13568:     }
1.1067    raeburn  13569:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13570:     if (keys(%toplevelitems) > 0) {
                   13571:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13572:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13573:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13574:     }
1.1066    raeburn  13575:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13576:     if ($numitems) {
                   13577:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13578:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13579:             my $path = $env{'form.archive_content_'.$i};
                   13580:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13581:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13582:                     if ($prefix ne '' && $path ne '') {
                   13583:                         if (-e $prefix.$path) {
1.1066    raeburn  13584:                             if ((@archdirs > 0) && 
                   13585:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13586:                                 $todeletedir{$prefix.$path} = 1;
                   13587:                             } else {
                   13588:                                 $todelete{$prefix.$path} = 1;
                   13589:                             }
1.1055    raeburn  13590:                         }
                   13591:                     }
                   13592:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13593:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13594:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13595:                     $docstitle = $env{'form.archive_title_'.$i};
                   13596:                     if ($docstitle eq '') {
                   13597:                         $docstitle = $title;
                   13598:                     }
1.1055    raeburn  13599:                     $outer = 0;
1.1056    raeburn  13600:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13601:                         if (@{$dirorder{$i}} > 0) {
                   13602:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13603:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13604:                                     $outer = $item;
                   13605:                                     last;
                   13606:                                 }
                   13607:                             }
                   13608:                         }
                   13609:                     }
                   13610:                     my ($errtext,$fatal) = 
                   13611:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13612:                                                '/'.$folders{$outer}.'.'.
                   13613:                                                $containers{$outer});
                   13614:                     next if ($fatal);
                   13615:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13616:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13617:                             $mapinner{$i} = time;
1.1055    raeburn  13618:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13619:                             $containers{$i} = 'sequence';
                   13620:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13621:                                       $folders{$i}.'.'.$containers{$i};
                   13622:                             my $newidx = &LONCAPA::map::getresidx();
                   13623:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13624:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13625:                             push(@LONCAPA::map::order,$newidx);
                   13626:                             my ($outtext,$errtext) =
                   13627:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13628:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13629:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13630:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13631:                             unless ($errtext) {
1.1294    raeburn  13632:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13633:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13634:                                             '</li>'."\n";
1.1067    raeburn  13635:                             }
1.1055    raeburn  13636:                         }
                   13637:                     } else {
                   13638:                         if ($context eq 'coursedocs') {
                   13639:                             my $newidx=&LONCAPA::map::getresidx();
                   13640:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13641:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13642:                                       $title;
1.1294    raeburn  13643:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13644:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13645:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13646:                                 }
                   13647:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13648:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13649:                                 }
                   13650:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13651:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13652:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13653:                                         unless ($ishome) {
                   13654:                                             my $fetch = "$newdest{$i}/$title";
                   13655:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13656:                                             $prompttofetch{$fetch} = 1;
                   13657:                                         }
1.1292    raeburn  13658:                                     }
1.1067    raeburn  13659:                                 }
1.1294    raeburn  13660:                                 $LONCAPA::map::resources[$newidx]=
                   13661:                                     $docstitle.':'.$url.':false:normal:res';
                   13662:                                 push(@LONCAPA::map::order, $newidx);
                   13663:                                 my ($outtext,$errtext)=
                   13664:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13665:                                                             $docuname.'/'.$folders{$outer}.
                   13666:                                                             '.'.$containers{$outer},1,1);
                   13667:                                 unless ($errtext) {
                   13668:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13669:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13670:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13671:                                                    '</li>'."\n";
                   13672:                                     }
1.1067    raeburn  13673:                                 }
1.1294    raeburn  13674:                             } else {
                   13675:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13676:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13677:                             }
1.1055    raeburn  13678:                         }
                   13679:                     }
1.1086    raeburn  13680:                 }
                   13681:             } else {
1.1294    raeburn  13682:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13683:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13684:             }
                   13685:         }
                   13686:         for (my $i=1; $i<=$numitems; $i++) {
                   13687:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13688:             my $path = $env{'form.archive_content_'.$i};
                   13689:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13690:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13691:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13692:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13693:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13694:                         my ($itemidx,$fullpath,$relpath);
                   13695:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13696:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13697:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13698:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13699:                                     $itemidx = $j;
1.1056    raeburn  13700:                                 }
                   13701:                             }
1.1086    raeburn  13702:                         }
                   13703:                         if ($itemidx eq '') {
                   13704:                             $itemidx =  0;
                   13705:                         } 
                   13706:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13707:                             if ($mapinner{$referrer{$i}}) {
                   13708:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13709:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13710:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13711:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13712:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13713:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13714:                                             if (!-e $fullpath) {
                   13715:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13716:                                             }
                   13717:                                         }
1.1086    raeburn  13718:                                     } else {
                   13719:                                         last;
1.1056    raeburn  13720:                                     }
1.1086    raeburn  13721:                                 }
                   13722:                             }
                   13723:                         } elsif ($newdest{$referrer{$i}}) {
                   13724:                             $fullpath = $newdest{$referrer{$i}};
                   13725:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13726:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13727:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13728:                                     last;
                   13729:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13730:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13731:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13732:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13733:                                         if (!-e $fullpath) {
                   13734:                                             mkdir($fullpath,0755);
1.1056    raeburn  13735:                                         }
                   13736:                                     }
1.1086    raeburn  13737:                                 } else {
                   13738:                                     last;
1.1056    raeburn  13739:                                 }
1.1055    raeburn  13740:                             }
                   13741:                         }
1.1086    raeburn  13742:                         if ($fullpath ne '') {
                   13743:                             if (-e "$prefix$path") {
1.1292    raeburn  13744:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13745:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13746:                                 }
1.1086    raeburn  13747:                             }
                   13748:                             if (-e "$fullpath/$title") {
                   13749:                                 my $showpath;
                   13750:                                 if ($relpath ne '') {
                   13751:                                     $showpath = "$relpath/$title";
                   13752:                                 } else {
                   13753:                                     $showpath = "/$title";
                   13754:                                 } 
1.1294    raeburn  13755:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13756:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13757:                                            '</li>'."\n";
1.1292    raeburn  13758:                                 unless ($ishome) {
                   13759:                                     my $fetch = "$fullpath/$title";
                   13760:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   13761:                                     $prompttofetch{$fetch} = 1;
                   13762:                                 }
1.1086    raeburn  13763:                             }
                   13764:                         }
1.1055    raeburn  13765:                     }
1.1086    raeburn  13766:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13767:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  13768:                                     &HTML::Entities::encode($path,'<>&"'),
                   13769:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13770:                                 '<br />';
1.1055    raeburn  13771:                 }
                   13772:             } else {
1.1294    raeburn  13773:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  13774:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13775:             }
                   13776:         }
                   13777:         if (keys(%todelete)) {
                   13778:             foreach my $key (keys(%todelete)) {
                   13779:                 unlink($key);
1.1066    raeburn  13780:             }
                   13781:         }
                   13782:         if (keys(%todeletedir)) {
                   13783:             foreach my $key (keys(%todeletedir)) {
                   13784:                 rmdir($key);
                   13785:             }
                   13786:         }
                   13787:         foreach my $dir (sort(keys(%is_dir))) {
                   13788:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13789:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13790:             }
                   13791:         }
1.1067    raeburn  13792:         if ($result ne '') {
                   13793:             $output .= '<ul>'."\n".
                   13794:                        $result."\n".
                   13795:                        '</ul>';
                   13796:         }
                   13797:         unless ($ishome) {
                   13798:             my $replicationfail;
                   13799:             foreach my $item (keys(%prompttofetch)) {
                   13800:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13801:                 unless ($fetchresult eq 'ok') {
                   13802:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13803:                 }
                   13804:             }
                   13805:             if ($replicationfail) {
                   13806:                 $output .= '<p class="LC_error">'.
                   13807:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13808:                            $replicationfail.
                   13809:                            '</ul></p>';
                   13810:             }
                   13811:         }
1.1055    raeburn  13812:     } else {
                   13813:         $warning = &mt('No items found in archive.');
                   13814:     }
                   13815:     if ($error) {
                   13816:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13817:                    $error.'</p>'."\n";
                   13818:     }
                   13819:     if ($warning) {
                   13820:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13821:     }
                   13822:     return $output;
                   13823: }
                   13824: 
1.1066    raeburn  13825: sub cleanup_empty_dirs {
                   13826:     my ($path) = @_;
                   13827:     if (($path ne '') && (-d $path)) {
                   13828:         if (opendir(my $dirh,$path)) {
                   13829:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13830:             my $numitems = 0;
                   13831:             foreach my $item (@dircontents) {
                   13832:                 if (-d "$path/$item") {
1.1111    raeburn  13833:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13834:                     if (-e "$path/$item") {
                   13835:                         $numitems ++;
                   13836:                     }
                   13837:                 } else {
                   13838:                     $numitems ++;
                   13839:                 }
                   13840:             }
                   13841:             if ($numitems == 0) {
                   13842:                 rmdir($path);
                   13843:             }
                   13844:             closedir($dirh);
                   13845:         }
                   13846:     }
                   13847:     return;
                   13848: }
                   13849: 
1.41      ng       13850: =pod
1.45      matthew  13851: 
1.1162    raeburn  13852: =item * &get_folder_hierarchy()
1.1068    raeburn  13853: 
                   13854: Provides hierarchy of names of folders/sub-folders containing the current
                   13855: item,
                   13856: 
                   13857: Inputs: 3
                   13858:      - $navmap - navmaps object
                   13859: 
                   13860:      - $map - url for map (either the trigger itself, or map containing
                   13861:                            the resource, which is the trigger).
                   13862: 
                   13863:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13864: 
                   13865: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13866: 
                   13867: =cut
                   13868: 
                   13869: sub get_folder_hierarchy {
                   13870:     my ($navmap,$map,$showitem) = @_;
                   13871:     my @pathitems;
                   13872:     if (ref($navmap)) {
                   13873:         my $mapres = $navmap->getResourceByUrl($map);
                   13874:         if (ref($mapres)) {
                   13875:             my $pcslist = $mapres->map_hierarchy();
                   13876:             if ($pcslist ne '') {
                   13877:                 my @pcs = split(/,/,$pcslist);
                   13878:                 foreach my $pc (@pcs) {
                   13879:                     if ($pc == 1) {
1.1129    raeburn  13880:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13881:                     } else {
                   13882:                         my $res = $navmap->getByMapPc($pc);
                   13883:                         if (ref($res)) {
                   13884:                             my $title = $res->compTitle();
                   13885:                             $title =~ s/\W+/_/g;
                   13886:                             if ($title ne '') {
                   13887:                                 push(@pathitems,$title);
                   13888:                             }
                   13889:                         }
                   13890:                     }
                   13891:                 }
                   13892:             }
1.1071    raeburn  13893:             if ($showitem) {
                   13894:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13895:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13896:                 } else {
                   13897:                     my $maptitle = $mapres->compTitle();
                   13898:                     $maptitle =~ s/\W+/_/g;
                   13899:                     if ($maptitle ne '') {
                   13900:                         push(@pathitems,$maptitle);
                   13901:                     }
1.1068    raeburn  13902:                 }
                   13903:             }
                   13904:         }
                   13905:     }
                   13906:     return @pathitems;
                   13907: }
                   13908: 
                   13909: =pod
                   13910: 
1.1015    raeburn  13911: =item * &get_turnedin_filepath()
                   13912: 
                   13913: Determines path in a user's portfolio file for storage of files uploaded
                   13914: to a specific essayresponse or dropbox item.
                   13915: 
                   13916: Inputs: 3 required + 1 optional.
                   13917: $symb is symb for resource, $uname and $udom are for current user (required).
                   13918: $caller is optional (can be "submission", if routine is called when storing
                   13919: an upoaded file when "Submit Answer" button was pressed).
                   13920: 
                   13921: Returns array containing $path and $multiresp. 
                   13922: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13923: than one file upload item.  Callers of routine should append partid as a 
                   13924: subdirectory to $path in cases where $multiresp is 1.
                   13925: 
                   13926: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13927: 
                   13928: =cut
                   13929: 
                   13930: sub get_turnedin_filepath {
                   13931:     my ($symb,$uname,$udom,$caller) = @_;
                   13932:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13933:     my $turnindir;
                   13934:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13935:     $turnindir = $userhash{'turnindir'};
                   13936:     my ($path,$multiresp);
                   13937:     if ($turnindir eq '') {
                   13938:         if ($caller eq 'submission') {
                   13939:             $turnindir = &mt('turned in');
                   13940:             $turnindir =~ s/\W+/_/g;
                   13941:             my %newhash = (
                   13942:                             'turnindir' => $turnindir,
                   13943:                           );
                   13944:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13945:         }
                   13946:     }
                   13947:     if ($turnindir ne '') {
                   13948:         $path = '/'.$turnindir.'/';
                   13949:         my ($multipart,$turnin,@pathitems);
                   13950:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13951:         if (defined($navmap)) {
                   13952:             my $mapres = $navmap->getResourceByUrl($map);
                   13953:             if (ref($mapres)) {
                   13954:                 my $pcslist = $mapres->map_hierarchy();
                   13955:                 if ($pcslist ne '') {
                   13956:                     foreach my $pc (split(/,/,$pcslist)) {
                   13957:                         my $res = $navmap->getByMapPc($pc);
                   13958:                         if (ref($res)) {
                   13959:                             my $title = $res->compTitle();
                   13960:                             $title =~ s/\W+/_/g;
                   13961:                             if ($title ne '') {
1.1149    raeburn  13962:                                 if (($pc > 1) && (length($title) > 12)) {
                   13963:                                     $title = substr($title,0,12);
                   13964:                                 }
1.1015    raeburn  13965:                                 push(@pathitems,$title);
                   13966:                             }
                   13967:                         }
                   13968:                     }
                   13969:                 }
                   13970:                 my $maptitle = $mapres->compTitle();
                   13971:                 $maptitle =~ s/\W+/_/g;
                   13972:                 if ($maptitle ne '') {
1.1149    raeburn  13973:                     if (length($maptitle) > 12) {
                   13974:                         $maptitle = substr($maptitle,0,12);
                   13975:                     }
1.1015    raeburn  13976:                     push(@pathitems,$maptitle);
                   13977:                 }
                   13978:                 unless ($env{'request.state'} eq 'construct') {
                   13979:                     my $res = $navmap->getBySymb($symb);
                   13980:                     if (ref($res)) {
                   13981:                         my $partlist = $res->parts();
                   13982:                         my $totaluploads = 0;
                   13983:                         if (ref($partlist) eq 'ARRAY') {
                   13984:                             foreach my $part (@{$partlist}) {
                   13985:                                 my @types = $res->responseType($part);
                   13986:                                 my @ids = $res->responseIds($part);
                   13987:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13988:                                     if ($types[$i] eq 'essay') {
                   13989:                                         my $partid = $part.'_'.$ids[$i];
                   13990:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13991:                                             $totaluploads ++;
                   13992:                                         }
                   13993:                                     }
                   13994:                                 }
                   13995:                             }
                   13996:                             if ($totaluploads > 1) {
                   13997:                                 $multiresp = 1;
                   13998:                             }
                   13999:                         }
                   14000:                     }
                   14001:                 }
                   14002:             } else {
                   14003:                 return;
                   14004:             }
                   14005:         } else {
                   14006:             return;
                   14007:         }
                   14008:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14009:         $restitle =~ s/\W+/_/g;
                   14010:         if ($restitle eq '') {
                   14011:             $restitle = ($resurl =~ m{/[^/]+$});
                   14012:             if ($restitle eq '') {
                   14013:                 $restitle = time;
                   14014:             }
                   14015:         }
1.1149    raeburn  14016:         if (length($restitle) > 12) {
                   14017:             $restitle = substr($restitle,0,12);
                   14018:         }
1.1015    raeburn  14019:         push(@pathitems,$restitle);
                   14020:         $path .= join('/',@pathitems);
                   14021:     }
                   14022:     return ($path,$multiresp);
                   14023: }
                   14024: 
                   14025: =pod
                   14026: 
1.464     albertel 14027: =back
1.41      ng       14028: 
1.112     bowersj2 14029: =head1 CSV Upload/Handling functions
1.38      albertel 14030: 
1.41      ng       14031: =over 4
                   14032: 
1.648     raeburn  14033: =item * &upfile_store($r)
1.41      ng       14034: 
                   14035: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14036: needs $env{'form.upfile'}
1.41      ng       14037: returns $datatoken to be put into hidden field
                   14038: 
                   14039: =cut
1.31      albertel 14040: 
                   14041: sub upfile_store {
                   14042:     my $r=shift;
1.258     albertel 14043:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14044:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14045:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14046:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14047: 
1.1299    raeburn  14048:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14049:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14050:                                      time.'_'.$$);
                   14051:     return if ($datatoken eq '');
                   14052: 
1.31      albertel 14053:     {
1.158     raeburn  14054:         my $datafile = $r->dir_config('lonDaemons').
                   14055:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14056:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14057:             print $fh $env{'form.upfile'};
1.158     raeburn  14058:             close($fh);
                   14059:         }
1.31      albertel 14060:     }
                   14061:     return $datatoken;
                   14062: }
                   14063: 
1.56      matthew  14064: =pod
                   14065: 
1.1290    raeburn  14066: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14067: 
                   14068: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14069: $datatoken is the name to assign to the temporary file.
1.258     albertel 14070: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14071: 
                   14072: =cut
1.31      albertel 14073: 
                   14074: sub load_tmp_file {
1.1290    raeburn  14075:     my ($r,$datatoken) = @_;
                   14076:     return if ($datatoken eq '');
1.31      albertel 14077:     my @studentdata=();
                   14078:     {
1.158     raeburn  14079:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14080:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14081:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14082:             @studentdata=<$fh>;
                   14083:             close($fh);
                   14084:         }
1.31      albertel 14085:     }
1.258     albertel 14086:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14087: }
                   14088: 
1.1290    raeburn  14089: sub valid_datatoken {
                   14090:     my ($datatoken) = @_;
1.1325    raeburn  14091:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14092:         return $datatoken;
                   14093:     }
                   14094:     return;
                   14095: }
                   14096: 
1.56      matthew  14097: =pod
                   14098: 
1.648     raeburn  14099: =item * &upfile_record_sep()
1.41      ng       14100: 
                   14101: Separate uploaded file into records
                   14102: returns array of records,
1.258     albertel 14103: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14104: 
                   14105: =cut
1.31      albertel 14106: 
                   14107: sub upfile_record_sep {
1.258     albertel 14108:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14109:     } else {
1.248     albertel 14110: 	my @records;
1.258     albertel 14111: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14112: 	    if ($line=~/^\s*$/) { next; }
                   14113: 	    push(@records,$line);
                   14114: 	}
                   14115: 	return @records;
1.31      albertel 14116:     }
                   14117: }
                   14118: 
1.56      matthew  14119: =pod
                   14120: 
1.648     raeburn  14121: =item * &record_sep($record)
1.41      ng       14122: 
1.258     albertel 14123: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14124: 
                   14125: =cut
                   14126: 
1.263     www      14127: sub takeleft {
                   14128:     my $index=shift;
                   14129:     return substr('0000'.$index,-4,4);
                   14130: }
                   14131: 
1.31      albertel 14132: sub record_sep {
                   14133:     my $record=shift;
                   14134:     my %components=();
1.258     albertel 14135:     if ($env{'form.upfiletype'} eq 'xml') {
                   14136:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14137:         my $i=0;
1.356     albertel 14138:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14139:             $field=~s/^(\"|\')//;
                   14140:             $field=~s/(\"|\')$//;
1.263     www      14141:             $components{&takeleft($i)}=$field;
1.31      albertel 14142:             $i++;
                   14143:         }
1.258     albertel 14144:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14145:         my $i=0;
1.356     albertel 14146:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14147:             $field=~s/^(\"|\')//;
                   14148:             $field=~s/(\"|\')$//;
1.263     www      14149:             $components{&takeleft($i)}=$field;
1.31      albertel 14150:             $i++;
                   14151:         }
                   14152:     } else {
1.561     www      14153:         my $separator=',';
1.480     banghart 14154:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14155:             $separator=';';
1.480     banghart 14156:         }
1.31      albertel 14157:         my $i=0;
1.561     www      14158: # the character we are looking for to indicate the end of a quote or a record 
                   14159:         my $looking_for=$separator;
                   14160: # do not add the characters to the fields
                   14161:         my $ignore=0;
                   14162: # we just encountered a separator (or the beginning of the record)
                   14163:         my $just_found_separator=1;
                   14164: # store the field we are working on here
                   14165:         my $field='';
                   14166: # work our way through all characters in record
                   14167:         foreach my $character ($record=~/(.)/g) {
                   14168:             if ($character eq $looking_for) {
                   14169:                if ($character ne $separator) {
                   14170: # Found the end of a quote, again looking for separator
                   14171:                   $looking_for=$separator;
                   14172:                   $ignore=1;
                   14173:                } else {
                   14174: # Found a separator, store away what we got
                   14175:                   $components{&takeleft($i)}=$field;
                   14176: 	          $i++;
                   14177:                   $just_found_separator=1;
                   14178:                   $ignore=0;
                   14179:                   $field='';
                   14180:                }
                   14181:                next;
                   14182:             }
                   14183: # single or double quotation marks after a separator indicate beginning of a quote
                   14184: # we are now looking for the end of the quote and need to ignore separators
                   14185:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14186:                $looking_for=$character;
                   14187:                next;
                   14188:             }
                   14189: # ignore would be true after we reached the end of a quote
                   14190:             if ($ignore) { next; }
                   14191:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14192:             $field.=$character;
                   14193:             $just_found_separator=0; 
1.31      albertel 14194:         }
1.561     www      14195: # catch the very last entry, since we never encountered the separator
                   14196:         $components{&takeleft($i)}=$field;
1.31      albertel 14197:     }
                   14198:     return %components;
                   14199: }
                   14200: 
1.144     matthew  14201: ######################################################
                   14202: ######################################################
                   14203: 
1.56      matthew  14204: =pod
                   14205: 
1.648     raeburn  14206: =item * &upfile_select_html()
1.41      ng       14207: 
1.144     matthew  14208: Return HTML code to select a file from the users machine and specify 
                   14209: the file type.
1.41      ng       14210: 
                   14211: =cut
                   14212: 
1.144     matthew  14213: ######################################################
                   14214: ######################################################
1.31      albertel 14215: sub upfile_select_html {
1.144     matthew  14216:     my %Types = (
                   14217:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14218:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14219:                  space => &mt('Space separated'),
                   14220:                  tab   => &mt('Tabulator separated'),
                   14221: #                 xml   => &mt('HTML/XML'),
                   14222:                  );
                   14223:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14224:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14225:     foreach my $type (sort(keys(%Types))) {
                   14226:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14227:     }
                   14228:     $Str .= "</select>\n";
                   14229:     return $Str;
1.31      albertel 14230: }
                   14231: 
1.301     albertel 14232: sub get_samples {
                   14233:     my ($records,$toget) = @_;
                   14234:     my @samples=({});
                   14235:     my $got=0;
                   14236:     foreach my $rec (@$records) {
                   14237: 	my %temp = &record_sep($rec);
                   14238: 	if (! grep(/\S/, values(%temp))) { next; }
                   14239: 	if (%temp) {
                   14240: 	    $samples[$got]=\%temp;
                   14241: 	    $got++;
                   14242: 	    if ($got == $toget) { last; }
                   14243: 	}
                   14244:     }
                   14245:     return \@samples;
                   14246: }
                   14247: 
1.144     matthew  14248: ######################################################
                   14249: ######################################################
                   14250: 
1.56      matthew  14251: =pod
                   14252: 
1.648     raeburn  14253: =item * &csv_print_samples($r,$records)
1.41      ng       14254: 
                   14255: Prints a table of sample values from each column uploaded $r is an
                   14256: Apache Request ref, $records is an arrayref from
                   14257: &Apache::loncommon::upfile_record_sep
                   14258: 
                   14259: =cut
                   14260: 
1.144     matthew  14261: ######################################################
                   14262: ######################################################
1.31      albertel 14263: sub csv_print_samples {
                   14264:     my ($r,$records) = @_;
1.662     bisitz   14265:     my $samples = &get_samples($records,5);
1.301     albertel 14266: 
1.594     raeburn  14267:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14268:               &start_data_table_header_row());
1.356     albertel 14269:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14270:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14271:     $r->print(&end_data_table_header_row());
1.301     albertel 14272:     foreach my $hash (@$samples) {
1.594     raeburn  14273: 	$r->print(&start_data_table_row());
1.356     albertel 14274: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14275: 	    $r->print('<td>');
1.356     albertel 14276: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14277: 	    $r->print('</td>');
                   14278: 	}
1.594     raeburn  14279: 	$r->print(&end_data_table_row());
1.31      albertel 14280:     }
1.594     raeburn  14281:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14282: }
                   14283: 
1.144     matthew  14284: ######################################################
                   14285: ######################################################
                   14286: 
1.56      matthew  14287: =pod
                   14288: 
1.648     raeburn  14289: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14290: 
                   14291: Prints a table to create associations between values and table columns.
1.144     matthew  14292: 
1.41      ng       14293: $r is an Apache Request ref,
                   14294: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14295: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14296: 
                   14297: =cut
                   14298: 
1.144     matthew  14299: ######################################################
                   14300: ######################################################
1.31      albertel 14301: sub csv_print_select_table {
                   14302:     my ($r,$records,$d) = @_;
1.301     albertel 14303:     my $i=0;
                   14304:     my $samples = &get_samples($records,1);
1.144     matthew  14305:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14306: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14307:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14308:               '<th>'.&mt('Column').'</th>'.
                   14309:               &end_data_table_header_row()."\n");
1.356     albertel 14310:     foreach my $array_ref (@$d) {
                   14311: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14312: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14313: 
1.875     bisitz   14314: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14315: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14316: 	$r->print('<option value="none"></option>');
1.356     albertel 14317: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14318: 	    $r->print('<option value="'.$sample.'"'.
                   14319:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14320:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14321: 	}
1.594     raeburn  14322: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14323: 	$i++;
                   14324:     }
1.594     raeburn  14325:     $r->print(&end_data_table());
1.31      albertel 14326:     $i--;
                   14327:     return $i;
                   14328: }
1.56      matthew  14329: 
1.144     matthew  14330: ######################################################
                   14331: ######################################################
                   14332: 
1.56      matthew  14333: =pod
1.31      albertel 14334: 
1.648     raeburn  14335: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14336: 
                   14337: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14338: 
                   14339: $r is an Apache Request ref,
                   14340: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14341: $d is an array of 2 element arrays (internal name, displayed name)
                   14342: 
                   14343: =cut
                   14344: 
1.144     matthew  14345: ######################################################
                   14346: ######################################################
1.31      albertel 14347: sub csv_samples_select_table {
                   14348:     my ($r,$records,$d) = @_;
                   14349:     my $i=0;
1.144     matthew  14350:     #
1.662     bisitz   14351:     my $max_samples = 5;
                   14352:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14353:     $r->print(&start_data_table().
                   14354:               &start_data_table_header_row().'<th>'.
                   14355:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14356:               &end_data_table_header_row());
1.301     albertel 14357: 
                   14358:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14359: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14360: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14361: 	foreach my $option (@$d) {
                   14362: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14363: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14364:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14365:                       $display.'</option>');
1.31      albertel 14366: 	}
                   14367: 	$r->print('</select></td><td>');
1.662     bisitz   14368: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14369: 	    if (defined($samples->[$line]{$key})) { 
                   14370: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14371: 	    }
                   14372: 	}
1.594     raeburn  14373: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14374: 	$i++;
                   14375:     }
1.594     raeburn  14376:     $r->print(&end_data_table());
1.31      albertel 14377:     $i--;
                   14378:     return($i);
1.115     matthew  14379: }
                   14380: 
1.144     matthew  14381: ######################################################
                   14382: ######################################################
                   14383: 
1.115     matthew  14384: =pod
                   14385: 
1.648     raeburn  14386: =item * &clean_excel_name($name)
1.115     matthew  14387: 
                   14388: Returns a replacement for $name which does not contain any illegal characters.
                   14389: 
                   14390: =cut
                   14391: 
1.144     matthew  14392: ######################################################
                   14393: ######################################################
1.115     matthew  14394: sub clean_excel_name {
                   14395:     my ($name) = @_;
                   14396:     $name =~ s/[:\*\?\/\\]//g;
                   14397:     if (length($name) > 31) {
                   14398:         $name = substr($name,0,31);
                   14399:     }
                   14400:     return $name;
1.25      albertel 14401: }
1.84      albertel 14402: 
1.85      albertel 14403: =pod
                   14404: 
1.648     raeburn  14405: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14406: 
                   14407: Returns either 1 or undef
                   14408: 
                   14409: 1 if the part is to be hidden, undef if it is to be shown
                   14410: 
                   14411: Arguments are:
                   14412: 
                   14413: $id the id of the part to be checked
                   14414: $symb, optional the symb of the resource to check
                   14415: $udom, optional the domain of the user to check for
                   14416: $uname, optional the username of the user to check for
                   14417: 
                   14418: =cut
1.84      albertel 14419: 
                   14420: sub check_if_partid_hidden {
                   14421:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14422:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14423: 					 $symb,$udom,$uname);
1.141     albertel 14424:     my $truth=1;
                   14425:     #if the string starts with !, then the list is the list to show not hide
                   14426:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14427:     my @hiddenlist=split(/,/,$hiddenparts);
                   14428:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14429: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14430:     }
1.141     albertel 14431:     return !$truth;
1.84      albertel 14432: }
1.127     matthew  14433: 
1.138     matthew  14434: 
                   14435: ############################################################
                   14436: ############################################################
                   14437: 
                   14438: =pod
                   14439: 
1.157     matthew  14440: =back 
                   14441: 
1.138     matthew  14442: =head1 cgi-bin script and graphing routines
                   14443: 
1.157     matthew  14444: =over 4
                   14445: 
1.648     raeburn  14446: =item * &get_cgi_id()
1.138     matthew  14447: 
                   14448: Inputs: none
                   14449: 
                   14450: Returns an id which can be used to pass environment variables
                   14451: to various cgi-bin scripts.  These environment variables will
                   14452: be removed from the users environment after a given time by
                   14453: the routine &Apache::lonnet::transfer_profile_to_env.
                   14454: 
                   14455: =cut
                   14456: 
                   14457: ############################################################
                   14458: ############################################################
1.152     albertel 14459: my $uniq=0;
1.136     matthew  14460: sub get_cgi_id {
1.154     albertel 14461:     $uniq=($uniq+1)%100000;
1.280     albertel 14462:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14463: }
                   14464: 
1.127     matthew  14465: ############################################################
                   14466: ############################################################
                   14467: 
                   14468: =pod
                   14469: 
1.648     raeburn  14470: =item * &DrawBarGraph()
1.127     matthew  14471: 
1.138     matthew  14472: Facilitates the plotting of data in a (stacked) bar graph.
                   14473: Puts plot definition data into the users environment in order for 
                   14474: graph.png to plot it.  Returns an <img> tag for the plot.
                   14475: The bars on the plot are labeled '1','2',...,'n'.
                   14476: 
                   14477: Inputs:
                   14478: 
                   14479: =over 4
                   14480: 
                   14481: =item $Title: string, the title of the plot
                   14482: 
                   14483: =item $xlabel: string, text describing the X-axis of the plot
                   14484: 
                   14485: =item $ylabel: string, text describing the Y-axis of the plot
                   14486: 
                   14487: =item $Max: scalar, the maximum Y value to use in the plot
                   14488: If $Max is < any data point, the graph will not be rendered.
                   14489: 
1.140     matthew  14490: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14491: they are plotted.  If undefined, default values will be used.
                   14492: 
1.178     matthew  14493: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14494: 
1.138     matthew  14495: =item @Values: An array of array references.  Each array reference holds data
                   14496: to be plotted in a stacked bar chart.
                   14497: 
1.239     matthew  14498: =item If the final element of @Values is a hash reference the key/value
                   14499: pairs will be added to the graph definition.
                   14500: 
1.138     matthew  14501: =back
                   14502: 
                   14503: Returns:
                   14504: 
                   14505: An <img> tag which references graph.png and the appropriate identifying
                   14506: information for the plot.
                   14507: 
1.127     matthew  14508: =cut
                   14509: 
                   14510: ############################################################
                   14511: ############################################################
1.134     matthew  14512: sub DrawBarGraph {
1.178     matthew  14513:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14514:     #
                   14515:     if (! defined($colors)) {
                   14516:         $colors = ['#33ff00', 
                   14517:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14518:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14519:                   ]; 
                   14520:     }
1.228     matthew  14521:     my $extra_settings = {};
                   14522:     if (ref($Values[-1]) eq 'HASH') {
                   14523:         $extra_settings = pop(@Values);
                   14524:     }
1.127     matthew  14525:     #
1.136     matthew  14526:     my $identifier = &get_cgi_id();
                   14527:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14528:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14529:         return '';
                   14530:     }
1.225     matthew  14531:     #
                   14532:     my @Labels;
                   14533:     if (defined($labels)) {
                   14534:         @Labels = @$labels;
                   14535:     } else {
                   14536:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14537:             push(@Labels,$i+1);
1.225     matthew  14538:         }
                   14539:     }
                   14540:     #
1.129     matthew  14541:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14542:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14543:     my %ValuesHash;
                   14544:     my $NumSets=1;
                   14545:     foreach my $array (@Values) {
                   14546:         next if (! ref($array));
1.136     matthew  14547:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14548:             join(',',@$array);
1.129     matthew  14549:     }
1.127     matthew  14550:     #
1.136     matthew  14551:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14552:     if ($NumBars < 3) {
                   14553:         $width = 120+$NumBars*32;
1.220     matthew  14554:         $xskip = 1;
1.225     matthew  14555:         $bar_width = 30;
                   14556:     } elsif ($NumBars < 5) {
                   14557:         $width = 120+$NumBars*20;
                   14558:         $xskip = 1;
                   14559:         $bar_width = 20;
1.220     matthew  14560:     } elsif ($NumBars < 10) {
1.136     matthew  14561:         $width = 120+$NumBars*15;
                   14562:         $xskip = 1;
                   14563:         $bar_width = 15;
                   14564:     } elsif ($NumBars <= 25) {
                   14565:         $width = 120+$NumBars*11;
                   14566:         $xskip = 5;
                   14567:         $bar_width = 8;
                   14568:     } elsif ($NumBars <= 50) {
                   14569:         $width = 120+$NumBars*8;
                   14570:         $xskip = 5;
                   14571:         $bar_width = 4;
                   14572:     } else {
                   14573:         $width = 120+$NumBars*8;
                   14574:         $xskip = 5;
                   14575:         $bar_width = 4;
                   14576:     }
                   14577:     #
1.137     matthew  14578:     $Max = 1 if ($Max < 1);
                   14579:     if ( int($Max) < $Max ) {
                   14580:         $Max++;
                   14581:         $Max = int($Max);
                   14582:     }
1.127     matthew  14583:     $Title  = '' if (! defined($Title));
                   14584:     $xlabel = '' if (! defined($xlabel));
                   14585:     $ylabel = '' if (! defined($ylabel));
1.369     www      14586:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14587:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14588:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14589:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14590:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14591:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14592:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14593:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14594:     $ValuesHash{$id.'.height'}   = $height;
                   14595:     $ValuesHash{$id.'.width'}    = $width;
                   14596:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14597:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14598:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14599:     #
1.228     matthew  14600:     # Deal with other parameters
                   14601:     while (my ($key,$value) = each(%$extra_settings)) {
                   14602:         $ValuesHash{$id.'.'.$key} = $value;
                   14603:     }
                   14604:     #
1.646     raeburn  14605:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14606:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14607: }
                   14608: 
                   14609: ############################################################
                   14610: ############################################################
                   14611: 
                   14612: =pod
                   14613: 
1.648     raeburn  14614: =item * &DrawXYGraph()
1.137     matthew  14615: 
1.138     matthew  14616: Facilitates the plotting of data in an XY graph.
                   14617: Puts plot definition data into the users environment in order for 
                   14618: graph.png to plot it.  Returns an <img> tag for the plot.
                   14619: 
                   14620: Inputs:
                   14621: 
                   14622: =over 4
                   14623: 
                   14624: =item $Title: string, the title of the plot
                   14625: 
                   14626: =item $xlabel: string, text describing the X-axis of the plot
                   14627: 
                   14628: =item $ylabel: string, text describing the Y-axis of the plot
                   14629: 
                   14630: =item $Max: scalar, the maximum Y value to use in the plot
                   14631: If $Max is < any data point, the graph will not be rendered.
                   14632: 
                   14633: =item $colors: Array ref containing the hex color codes for the data to be 
                   14634: plotted in.  If undefined, default values will be used.
                   14635: 
                   14636: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14637: 
                   14638: =item $Ydata: Array ref containing Array refs.  
1.185     www      14639: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14640: 
                   14641: =item %Values: hash indicating or overriding any default values which are 
                   14642: passed to graph.png.  
                   14643: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14644: 
                   14645: =back
                   14646: 
                   14647: Returns:
                   14648: 
                   14649: An <img> tag which references graph.png and the appropriate identifying
                   14650: information for the plot.
                   14651: 
1.137     matthew  14652: =cut
                   14653: 
                   14654: ############################################################
                   14655: ############################################################
                   14656: sub DrawXYGraph {
                   14657:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14658:     #
                   14659:     # Create the identifier for the graph
                   14660:     my $identifier = &get_cgi_id();
                   14661:     my $id = 'cgi.'.$identifier;
                   14662:     #
                   14663:     $Title  = '' if (! defined($Title));
                   14664:     $xlabel = '' if (! defined($xlabel));
                   14665:     $ylabel = '' if (! defined($ylabel));
                   14666:     my %ValuesHash = 
                   14667:         (
1.369     www      14668:          $id.'.title'  => &escape($Title),
                   14669:          $id.'.xlabel' => &escape($xlabel),
                   14670:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14671:          $id.'.y_max_value'=> $Max,
                   14672:          $id.'.labels'     => join(',',@$Xlabels),
                   14673:          $id.'.PlotType'   => 'XY',
                   14674:          );
                   14675:     #
                   14676:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14677:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14678:     }
                   14679:     #
                   14680:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14681:         return '';
                   14682:     }
                   14683:     my $NumSets=1;
1.138     matthew  14684:     foreach my $array (@{$Ydata}){
1.137     matthew  14685:         next if (! ref($array));
                   14686:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14687:     }
1.138     matthew  14688:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14689:     #
                   14690:     # Deal with other parameters
                   14691:     while (my ($key,$value) = each(%Values)) {
                   14692:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14693:     }
                   14694:     #
1.646     raeburn  14695:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14696:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14697: }
                   14698: 
                   14699: ############################################################
                   14700: ############################################################
                   14701: 
                   14702: =pod
                   14703: 
1.648     raeburn  14704: =item * &DrawXYYGraph()
1.138     matthew  14705: 
                   14706: Facilitates the plotting of data in an XY graph with two Y axes.
                   14707: Puts plot definition data into the users environment in order for 
                   14708: graph.png to plot it.  Returns an <img> tag for the plot.
                   14709: 
                   14710: Inputs:
                   14711: 
                   14712: =over 4
                   14713: 
                   14714: =item $Title: string, the title of the plot
                   14715: 
                   14716: =item $xlabel: string, text describing the X-axis of the plot
                   14717: 
                   14718: =item $ylabel: string, text describing the Y-axis of the plot
                   14719: 
                   14720: =item $colors: Array ref containing the hex color codes for the data to be 
                   14721: plotted in.  If undefined, default values will be used.
                   14722: 
                   14723: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14724: 
                   14725: =item $Ydata1: The first data set
                   14726: 
                   14727: =item $Min1: The minimum value of the left Y-axis
                   14728: 
                   14729: =item $Max1: The maximum value of the left Y-axis
                   14730: 
                   14731: =item $Ydata2: The second data set
                   14732: 
                   14733: =item $Min2: The minimum value of the right Y-axis
                   14734: 
                   14735: =item $Max2: The maximum value of the left Y-axis
                   14736: 
                   14737: =item %Values: hash indicating or overriding any default values which are 
                   14738: passed to graph.png.  
                   14739: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14740: 
                   14741: =back
                   14742: 
                   14743: Returns:
                   14744: 
                   14745: An <img> tag which references graph.png and the appropriate identifying
                   14746: information for the plot.
1.136     matthew  14747: 
                   14748: =cut
                   14749: 
                   14750: ############################################################
                   14751: ############################################################
1.137     matthew  14752: sub DrawXYYGraph {
                   14753:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14754:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14755:     #
                   14756:     # Create the identifier for the graph
                   14757:     my $identifier = &get_cgi_id();
                   14758:     my $id = 'cgi.'.$identifier;
                   14759:     #
                   14760:     $Title  = '' if (! defined($Title));
                   14761:     $xlabel = '' if (! defined($xlabel));
                   14762:     $ylabel = '' if (! defined($ylabel));
                   14763:     my %ValuesHash = 
                   14764:         (
1.369     www      14765:          $id.'.title'  => &escape($Title),
                   14766:          $id.'.xlabel' => &escape($xlabel),
                   14767:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14768:          $id.'.labels' => join(',',@$Xlabels),
                   14769:          $id.'.PlotType' => 'XY',
                   14770:          $id.'.NumSets' => 2,
1.137     matthew  14771:          $id.'.two_axes' => 1,
                   14772:          $id.'.y1_max_value' => $Max1,
                   14773:          $id.'.y1_min_value' => $Min1,
                   14774:          $id.'.y2_max_value' => $Max2,
                   14775:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14776:          );
                   14777:     #
1.137     matthew  14778:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14779:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14780:     }
                   14781:     #
                   14782:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14783:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14784:         return '';
                   14785:     }
                   14786:     my $NumSets=1;
1.137     matthew  14787:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14788:         next if (! ref($array));
                   14789:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14790:     }
                   14791:     #
                   14792:     # Deal with other parameters
                   14793:     while (my ($key,$value) = each(%Values)) {
                   14794:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14795:     }
                   14796:     #
1.646     raeburn  14797:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14798:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14799: }
                   14800: 
                   14801: ############################################################
                   14802: ############################################################
                   14803: 
                   14804: =pod
                   14805: 
1.157     matthew  14806: =back 
                   14807: 
1.139     matthew  14808: =head1 Statistics helper routines?  
                   14809: 
                   14810: Bad place for them but what the hell.
                   14811: 
1.157     matthew  14812: =over 4
                   14813: 
1.648     raeburn  14814: =item * &chartlink()
1.139     matthew  14815: 
                   14816: Returns a link to the chart for a specific student.  
                   14817: 
                   14818: Inputs:
                   14819: 
                   14820: =over 4
                   14821: 
                   14822: =item $linktext: The text of the link
                   14823: 
                   14824: =item $sname: The students username
                   14825: 
                   14826: =item $sdomain: The students domain
                   14827: 
                   14828: =back
                   14829: 
1.157     matthew  14830: =back
                   14831: 
1.139     matthew  14832: =cut
                   14833: 
                   14834: ############################################################
                   14835: ############################################################
                   14836: sub chartlink {
                   14837:     my ($linktext, $sname, $sdomain) = @_;
                   14838:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14839:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14840:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14841:        '">'.$linktext.'</a>';
1.153     matthew  14842: }
                   14843: 
                   14844: #######################################################
                   14845: #######################################################
                   14846: 
                   14847: =pod
                   14848: 
                   14849: =head1 Course Environment Routines
1.157     matthew  14850: 
                   14851: =over 4
1.153     matthew  14852: 
1.648     raeburn  14853: =item * &restore_course_settings()
1.153     matthew  14854: 
1.648     raeburn  14855: =item * &store_course_settings()
1.153     matthew  14856: 
                   14857: Restores/Store indicated form parameters from the course environment.
                   14858: Will not overwrite existing values of the form parameters.
                   14859: 
                   14860: Inputs: 
                   14861: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14862: 
                   14863: a hash ref describing the data to be stored.  For example:
                   14864:    
                   14865: %Save_Parameters = ('Status' => 'scalar',
                   14866:     'chartoutputmode' => 'scalar',
                   14867:     'chartoutputdata' => 'scalar',
                   14868:     'Section' => 'array',
1.373     raeburn  14869:     'Group' => 'array',
1.153     matthew  14870:     'StudentData' => 'array',
                   14871:     'Maps' => 'array');
                   14872: 
                   14873: Returns: both routines return nothing
                   14874: 
1.631     raeburn  14875: =back
                   14876: 
1.153     matthew  14877: =cut
                   14878: 
                   14879: #######################################################
                   14880: #######################################################
                   14881: sub store_course_settings {
1.496     albertel 14882:     return &store_settings($env{'request.course.id'},@_);
                   14883: }
                   14884: 
                   14885: sub store_settings {
1.153     matthew  14886:     # save to the environment
                   14887:     # appenv the same items, just to be safe
1.300     albertel 14888:     my $udom  = $env{'user.domain'};
                   14889:     my $uname = $env{'user.name'};
1.496     albertel 14890:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14891:     my %SaveHash;
                   14892:     my %AppHash;
                   14893:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14894:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14895:         my $envname = 'environment.'.$basename;
1.258     albertel 14896:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14897:             # Save this value away
                   14898:             if ($type eq 'scalar' &&
1.258     albertel 14899:                 (! exists($env{$envname}) || 
                   14900:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14901:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14902:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14903:             } elsif ($type eq 'array') {
                   14904:                 my $stored_form;
1.258     albertel 14905:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14906:                     $stored_form = join(',',
                   14907:                                         map {
1.369     www      14908:                                             &escape($_);
1.258     albertel 14909:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14910:                 } else {
                   14911:                     $stored_form = 
1.369     www      14912:                         &escape($env{'form.'.$setting});
1.153     matthew  14913:                 }
                   14914:                 # Determine if the array contents are the same.
1.258     albertel 14915:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14916:                     $SaveHash{$basename} = $stored_form;
                   14917:                     $AppHash{$envname}   = $stored_form;
                   14918:                 }
                   14919:             }
                   14920:         }
                   14921:     }
                   14922:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14923:                                           $udom,$uname);
1.153     matthew  14924:     if ($put_result !~ /^(ok|delayed)/) {
                   14925:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14926:                                  'got error:'.$put_result);
                   14927:     }
                   14928:     # Make sure these settings stick around in this session, too
1.646     raeburn  14929:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14930:     return;
                   14931: }
                   14932: 
                   14933: sub restore_course_settings {
1.499     albertel 14934:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14935: }
                   14936: 
                   14937: sub restore_settings {
                   14938:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14939:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14940:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14941:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14942:             '.'.$setting;
1.258     albertel 14943:         if (exists($env{$envname})) {
1.153     matthew  14944:             if ($type eq 'scalar') {
1.258     albertel 14945:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14946:             } elsif ($type eq 'array') {
1.258     albertel 14947:                 $env{'form.'.$setting} = [ 
1.153     matthew  14948:                                            map { 
1.369     www      14949:                                                &unescape($_); 
1.258     albertel 14950:                                            } split(',',$env{$envname})
1.153     matthew  14951:                                            ];
                   14952:             }
                   14953:         }
                   14954:     }
1.127     matthew  14955: }
                   14956: 
1.618     raeburn  14957: #######################################################
                   14958: #######################################################
                   14959: 
                   14960: =pod
                   14961: 
                   14962: =head1 Domain E-mail Routines  
                   14963: 
                   14964: =over 4
                   14965: 
1.648     raeburn  14966: =item * &build_recipient_list()
1.618     raeburn  14967: 
1.1144    raeburn  14968: Build recipient lists for following types of e-mail:
1.766     raeburn  14969: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14970: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14971: module change checking, student/employee ID conflict checks, as
                   14972: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14973: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14974: 
                   14975: Inputs:
1.619     raeburn  14976: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14977: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14978: requestsmail, updatesmail, or idconflictsmail).
                   14979: 
1.619     raeburn  14980: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14981: 
1.619     raeburn  14982: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  14983: i.e., predates configuration by DC via domainprefs.pm
                   14984: 
                   14985: $requname username of requester (if mailing type is helpdeskmail)
                   14986: 
                   14987: $requdom domain of requester (if mailing type is helpdeskmail)
                   14988: 
                   14989: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14990: 
1.618     raeburn  14991: 
1.655     raeburn  14992: Returns: comma separated list of addresses to which to send e-mail.
                   14993: 
                   14994: =back
1.618     raeburn  14995: 
                   14996: =cut
                   14997: 
                   14998: ############################################################
                   14999: ############################################################
                   15000: sub build_recipient_list {
1.1297    raeburn  15001:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15002:     my @recipients;
1.1270    raeburn  15003:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15004:     my %domconfig =
1.1270    raeburn  15005:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15006:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15007:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15008:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15009:                 my @contacts = ('adminemail','supportemail');
                   15010:                 foreach my $item (@contacts) {
                   15011:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15012:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15013:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15014:                             push(@recipients,$addr);
                   15015:                         }
1.619     raeburn  15016:                     }
1.1270    raeburn  15017:                 }
                   15018:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15019:                 if ($mailing eq 'helpdeskmail') {
                   15020:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15021:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15022:                         my @ok_bccs;
                   15023:                         foreach my $bcc (@bccs) {
                   15024:                             $bcc =~ s/^\s+//g;
                   15025:                             $bcc =~ s/\s+$//g;
                   15026:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15027:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15028:                                     push(@ok_bccs,$bcc);
                   15029:                                 }
                   15030:                             }
                   15031:                         }
                   15032:                         if (@ok_bccs > 0) {
                   15033:                             $allbcc = join(', ',@ok_bccs);
                   15034:                         }
                   15035:                     }
                   15036:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15037:                 }
                   15038:             }
1.766     raeburn  15039:         } elsif ($origmail ne '') {
1.1270    raeburn  15040:             $lastresort = $origmail;
1.618     raeburn  15041:         }
1.1297    raeburn  15042:         if ($mailing eq 'helpdeskmail') {
                   15043:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15044:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15045:                 my ($inststatus,$inststatus_checked);
                   15046:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15047:                     ($env{'user.domain'} ne 'public')) {
                   15048:                     $inststatus_checked = 1;
                   15049:                     $inststatus = $env{'environment.inststatus'};
                   15050:                 }
                   15051:                 unless ($inststatus_checked) {
                   15052:                     if (($requname ne '') && ($requdom ne '')) {
                   15053:                         if (($requname =~ /^$match_username$/) &&
                   15054:                             ($requdom =~ /^$match_domain$/) &&
                   15055:                             (&Apache::lonnet::domain($requdom))) {
                   15056:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15057:                                                                       $requdom);
                   15058:                             unless ($requhome eq 'no_host') {
                   15059:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15060:                                 $inststatus = $userenv{'inststatus'};
                   15061:                                 $inststatus_checked = 1;
                   15062:                             }
                   15063:                         }
                   15064:                     }
                   15065:                 }
                   15066:                 unless ($inststatus_checked) {
                   15067:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15068:                         my %srch = (srchby     => 'email',
                   15069:                                     srchdomain => $defdom,
                   15070:                                     srchterm   => $reqemail,
                   15071:                                     srchtype   => 'exact');
                   15072:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15073:                         foreach my $uname (keys(%srch_results)) {
                   15074:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15075:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15076:                                 $inststatus_checked = 1;
                   15077:                                 last;
                   15078:                             }
                   15079:                         }
                   15080:                         unless ($inststatus_checked) {
                   15081:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15082:                             if ($dirsrchres eq 'ok') {
                   15083:                                 foreach my $uname (keys(%srch_results)) {
                   15084:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15085:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15086:                                         $inststatus_checked = 1;
                   15087:                                         last;
                   15088:                                     }
                   15089:                                 }
                   15090:                             }
                   15091:                         }
                   15092:                     }
                   15093:                 }
                   15094:                 if ($inststatus ne '') {
                   15095:                     foreach my $status (split(/\:/,$inststatus)) {
                   15096:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15097:                             my @contacts = ('adminemail','supportemail');
                   15098:                             foreach my $item (@contacts) {
                   15099:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15100:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15101:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15102:                                         push(@recipients,$addr);
                   15103:                                     }
                   15104:                                 }
                   15105:                             }
                   15106:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15107:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15108:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15109:                                 my @ok_bccs;
                   15110:                                 foreach my $bcc (@bccs) {
                   15111:                                     $bcc =~ s/^\s+//g;
                   15112:                                     $bcc =~ s/\s+$//g;
                   15113:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15114:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15115:                                             push(@ok_bccs,$bcc);
                   15116:                                         }
                   15117:                                     }
                   15118:                                 }
                   15119:                                 if (@ok_bccs > 0) {
                   15120:                                     $allbcc = join(', ',@ok_bccs);
                   15121:                                 }
                   15122:                             }
                   15123:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15124:                             last;
                   15125:                         }
                   15126:                     }
                   15127:                 }
                   15128:             }
                   15129:         }
1.619     raeburn  15130:     } elsif ($origmail ne '') {
1.1270    raeburn  15131:         $lastresort = $origmail;
                   15132:     }
1.1297    raeburn  15133:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15134:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15135:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15136:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15137:             my %what = (
                   15138:                           perlvar => 1,
                   15139:                        );
                   15140:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15141:             if ($primary) {
                   15142:                 my $gotaddr;
                   15143:                 my ($result,$returnhash) =
                   15144:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15145:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15146:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15147:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15148:                         $gotaddr = 1;
                   15149:                     }
                   15150:                 }
                   15151:                 unless ($gotaddr) {
                   15152:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15153:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15154:                     unless ($uintdom eq $intdom) {
                   15155:                         my %domconfig =
                   15156:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15157:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15158:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15159:                                 my @contacts = ('adminemail','supportemail');
                   15160:                                 foreach my $item (@contacts) {
                   15161:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15162:                                         my $addr = $domconfig{'contacts'}{$item};
                   15163:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15164:                                             push(@recipients,$addr);
                   15165:                                         }
                   15166:                                     }
                   15167:                                 }
                   15168:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15169:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15170:                                 }
                   15171:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15172:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15173:                                     my @ok_bccs;
                   15174:                                     foreach my $bcc (@bccs) {
                   15175:                                         $bcc =~ s/^\s+//g;
                   15176:                                         $bcc =~ s/\s+$//g;
                   15177:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15178:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15179:                                                 push(@ok_bccs,$bcc);
                   15180:                                             }
                   15181:                                         }
                   15182:                                     }
                   15183:                                     if (@ok_bccs > 0) {
                   15184:                                         $allbcc = join(', ',@ok_bccs);
                   15185:                                     }
                   15186:                                 }
                   15187:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15188:                             }
                   15189:                         }
                   15190:                     }
                   15191:                 }
                   15192:             }
                   15193:         }
1.618     raeburn  15194:     }
1.688     raeburn  15195:     if (defined($defmail)) {
                   15196:         if ($defmail ne '') {
                   15197:             push(@recipients,$defmail);
                   15198:         }
1.618     raeburn  15199:     }
                   15200:     if ($otheremails) {
1.619     raeburn  15201:         my @others;
                   15202:         if ($otheremails =~ /,/) {
                   15203:             @others = split(/,/,$otheremails);
1.618     raeburn  15204:         } else {
1.619     raeburn  15205:             push(@others,$otheremails);
                   15206:         }
                   15207:         foreach my $addr (@others) {
                   15208:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15209:                 push(@recipients,$addr);
                   15210:             }
1.618     raeburn  15211:         }
                   15212:     }
1.1298    raeburn  15213:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15214:         if ((!@recipients) && ($lastresort ne '')) {
                   15215:             push(@recipients,$lastresort);
                   15216:         }
                   15217:     } elsif ($lastresort ne '') {
                   15218:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15219:             push(@recipients,$lastresort);
                   15220:         }
                   15221:     }
1.1271    raeburn  15222:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15223:     if (wantarray) {
                   15224:         return ($recipientlist,$allbcc,$addtext);
                   15225:     } else {
                   15226:         return $recipientlist;
                   15227:     }
1.618     raeburn  15228: }
                   15229: 
1.127     matthew  15230: ############################################################
                   15231: ############################################################
1.154     albertel 15232: 
1.655     raeburn  15233: =pod
                   15234: 
1.1224    musolffc 15235: =over 4
                   15236: 
1.1223    musolffc 15237: =item * &mime_email()
                   15238: 
                   15239: Sends an email with a possible attachment
                   15240: 
                   15241: Inputs:
                   15242: 
                   15243: =over 4
                   15244: 
                   15245: from -              Sender's email address
                   15246: 
1.1343    raeburn  15247: replyto -           Reply-To email address
                   15248: 
1.1223    musolffc 15249: to -                Email address of recipient
                   15250: 
                   15251: subject -           Subject of email
                   15252: 
                   15253: body -              Body of email
                   15254: 
                   15255: cc_string -         Carbon copy email address
                   15256: 
                   15257: bcc -               Blind carbon copy email address
                   15258: 
                   15259: attachment_path -   Path of file to be attached
                   15260: 
                   15261: file_name -         Name of file to be attached
                   15262: 
                   15263: attachment_text -   The body of an attachment of type "TEXT"
                   15264: 
                   15265: =back
                   15266: 
                   15267: =back
                   15268: 
                   15269: =cut
                   15270: 
                   15271: ############################################################
                   15272: ############################################################
                   15273: 
                   15274: sub mime_email {
1.1343    raeburn  15275:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15276:         $file_name,$attachment_text) = @_;
                   15277:  
1.1223    musolffc 15278:     my $msg = MIME::Lite->new(
                   15279:              From    => $from,
                   15280:              To      => $to,
                   15281:              Subject => $subject,
                   15282:              Type    =>'TEXT',
                   15283:              Data    => $body,
                   15284:              );
1.1343    raeburn  15285:     if ($replyto ne '') {
                   15286:         $msg->add("Reply-To" => $replyto);
                   15287:     }
1.1223    musolffc 15288:     if ($cc_string ne '') {
                   15289:         $msg->add("Cc" => $cc_string);
                   15290:     }
                   15291:     if ($bcc ne '') {
                   15292:         $msg->add("Bcc" => $bcc);
                   15293:     }
                   15294:     $msg->attr("content-type"         => "text/plain");
                   15295:     $msg->attr("content-type.charset" => "UTF-8");
                   15296:     # Attach file if given
                   15297:     if ($attachment_path) {
                   15298:         unless ($file_name) {
                   15299:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15300:         }
                   15301:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15302:         $msg->attach(Type     => $type,
                   15303:                      Path     => $attachment_path,
                   15304:                      Filename => $file_name
                   15305:                      );
                   15306:     # Otherwise attach text if given
                   15307:     } elsif ($attachment_text) {
                   15308:         $msg->attach(Type => 'TEXT',
                   15309:                      Data => $attachment_text);
                   15310:     }
                   15311:     # Send it
                   15312:     $msg->send('sendmail');
                   15313: }
                   15314: 
                   15315: ############################################################
                   15316: ############################################################
                   15317: 
                   15318: =pod
                   15319: 
1.655     raeburn  15320: =head1 Course Catalog Routines
                   15321: 
                   15322: =over 4
                   15323: 
                   15324: =item * &gather_categories()
                   15325: 
                   15326: Converts category definitions - keys of categories hash stored in  
                   15327: coursecategories in configuration.db on the primary library server in a 
                   15328: domain - to an array.  Also generates javascript and idx hash used to 
                   15329: generate Domain Coordinator interface for editing Course Categories.
                   15330: 
                   15331: Inputs:
1.663     raeburn  15332: 
1.655     raeburn  15333: categories (reference to hash of category definitions).
1.663     raeburn  15334: 
1.655     raeburn  15335: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15336:       categories and subcategories).
1.663     raeburn  15337: 
1.655     raeburn  15338: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15339:       editing Course Categories).
1.663     raeburn  15340: 
1.655     raeburn  15341: jsarray (reference to array of categories used to create Javascript arrays for
                   15342:          Domain Coordinator interface for editing Course Categories).
                   15343: 
                   15344: Returns: nothing
                   15345: 
                   15346: Side effects: populates cats, idx and jsarray. 
                   15347: 
                   15348: =cut
                   15349: 
                   15350: sub gather_categories {
                   15351:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15352:     my %counters;
                   15353:     my $num = 0;
                   15354:     foreach my $item (keys(%{$categories})) {
                   15355:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15356:         if ($container eq '' && $depth == 0) {
                   15357:             $cats->[$depth][$categories->{$item}] = $cat;
                   15358:         } else {
                   15359:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15360:         }
                   15361:         my ($escitem,$tail) = split(/:/,$item,2);
                   15362:         if ($counters{$tail} eq '') {
                   15363:             $counters{$tail} = $num;
                   15364:             $num ++;
                   15365:         }
                   15366:         if (ref($idx) eq 'HASH') {
                   15367:             $idx->{$item} = $counters{$tail};
                   15368:         }
                   15369:         if (ref($jsarray) eq 'ARRAY') {
                   15370:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15371:         }
                   15372:     }
                   15373:     return;
                   15374: }
                   15375: 
                   15376: =pod
                   15377: 
                   15378: =item * &extract_categories()
                   15379: 
                   15380: Used to generate breadcrumb trails for course categories.
                   15381: 
                   15382: Inputs:
1.663     raeburn  15383: 
1.655     raeburn  15384: categories (reference to hash of category definitions).
1.663     raeburn  15385: 
1.655     raeburn  15386: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15387:       categories and subcategories).
1.663     raeburn  15388: 
1.655     raeburn  15389: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15390: 
1.655     raeburn  15391: allitems (reference to hash - key is category key 
                   15392:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15393: 
1.655     raeburn  15394: idx (reference to hash of counters used in Domain Coordinator interface for
                   15395:       editing Course Categories).
1.663     raeburn  15396: 
1.655     raeburn  15397: jsarray (reference to array of categories used to create Javascript arrays for
                   15398:          Domain Coordinator interface for editing Course Categories).
                   15399: 
1.665     raeburn  15400: subcats (reference to hash of arrays containing all subcategories within each 
                   15401:          category, -recursive)
                   15402: 
1.1321    raeburn  15403: maxd (reference to hash used to hold max depth for all top-level categories).
                   15404: 
1.655     raeburn  15405: Returns: nothing
                   15406: 
                   15407: Side effects: populates trails and allitems hash references.
                   15408: 
                   15409: =cut
                   15410: 
                   15411: sub extract_categories {
1.1321    raeburn  15412:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15413:     if (ref($categories) eq 'HASH') {
                   15414:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15415:         if (ref($cats->[0]) eq 'ARRAY') {
                   15416:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15417:                 my $name = $cats->[0][$i];
                   15418:                 my $item = &escape($name).'::0';
                   15419:                 my $trailstr;
                   15420:                 if ($name eq 'instcode') {
                   15421:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15422:                 } elsif ($name eq 'communities') {
                   15423:                     $trailstr = &mt('Communities');
1.1239    raeburn  15424:                 } elsif ($name eq 'placement') {
                   15425:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15426:                 } else {
                   15427:                     $trailstr = $name;
                   15428:                 }
                   15429:                 if ($allitems->{$item} eq '') {
                   15430:                     push(@{$trails},$trailstr);
                   15431:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15432:                 }
                   15433:                 my @parents = ($name);
                   15434:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15435:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15436:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15437:                         if (ref($subcats) eq 'HASH') {
                   15438:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15439:                         }
1.1321    raeburn  15440:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15441:                     }
                   15442:                 } else {
                   15443:                     if (ref($subcats) eq 'HASH') {
                   15444:                         $subcats->{$item} = [];
1.655     raeburn  15445:                     }
1.1321    raeburn  15446:                     if (ref($maxd) eq 'HASH') {
                   15447:                         $maxd->{$name} = 1;
                   15448:                     }
1.655     raeburn  15449:                 }
                   15450:             }
                   15451:         }
                   15452:     }
                   15453:     return;
                   15454: }
                   15455: 
                   15456: =pod
                   15457: 
1.1162    raeburn  15458: =item * &recurse_categories()
1.655     raeburn  15459: 
                   15460: Recursively used to generate breadcrumb trails for course categories.
                   15461: 
                   15462: Inputs:
1.663     raeburn  15463: 
1.655     raeburn  15464: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15465:       categories and subcategories).
1.663     raeburn  15466: 
1.655     raeburn  15467: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15468: 
                   15469: category (current course category, for which breadcrumb trail is being generated).
                   15470: 
                   15471: trails (reference to array of breadcrumb trails for each category).
                   15472: 
1.655     raeburn  15473: allitems (reference to hash - key is category key
                   15474:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15475: 
1.655     raeburn  15476: parents (array containing containers directories for current category, 
                   15477:          back to top level). 
                   15478: 
                   15479: Returns: nothing
                   15480: 
                   15481: Side effects: populates trails and allitems hash references
                   15482: 
                   15483: =cut
                   15484: 
                   15485: sub recurse_categories {
1.1321    raeburn  15486:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15487:     my $shallower = $depth - 1;
                   15488:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15489:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15490:             my $name = $cats->[$depth]{$category}[$k];
                   15491:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15492:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15493:             if ($allitems->{$item} eq '') {
                   15494:                 push(@{$trails},$trailstr);
                   15495:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15496:             }
                   15497:             my $deeper = $depth+1;
                   15498:             push(@{$parents},$category);
1.665     raeburn  15499:             if (ref($subcats) eq 'HASH') {
                   15500:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15501:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15502:                     my $higher;
                   15503:                     if ($j > 0) {
                   15504:                         $higher = &escape($parents->[$j]).':'.
                   15505:                                   &escape($parents->[$j-1]).':'.$j;
                   15506:                     } else {
                   15507:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15508:                     }
                   15509:                     push(@{$subcats->{$higher}},$subcat);
                   15510:                 }
                   15511:             }
                   15512:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  15513:                                 $subcats,$maxd);
1.655     raeburn  15514:             pop(@{$parents});
                   15515:         }
                   15516:     } else {
                   15517:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15518:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15519:         if ($allitems->{$item} eq '') {
                   15520:             push(@{$trails},$trailstr);
                   15521:             $allitems->{$item} = scalar(@{$trails})-1;
                   15522:         }
1.1321    raeburn  15523:         if (ref($maxd) eq 'HASH') {
                   15524:             if ($depth > $maxd->{$parents->[0]}) {
                   15525:                 $maxd->{$parents->[0]} = $depth;
                   15526:             }
                   15527:         }
1.655     raeburn  15528:     }
                   15529:     return;
                   15530: }
                   15531: 
1.663     raeburn  15532: =pod
                   15533: 
1.1162    raeburn  15534: =item * &assign_categories_table()
1.663     raeburn  15535: 
                   15536: Create a datatable for display of hierarchical categories in a domain,
                   15537: with checkboxes to allow a course to be categorized. 
                   15538: 
                   15539: Inputs:
                   15540: 
                   15541: cathash - reference to hash of categories defined for the domain (from
                   15542:           configuration.db)
                   15543: 
                   15544: currcat - scalar with an & separated list of categories assigned to a course. 
                   15545: 
1.919     raeburn  15546: type    - scalar contains course type (Course or Community).
                   15547: 
1.1260    raeburn  15548: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15549:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15550: 
1.663     raeburn  15551: Returns: $output (markup to be displayed) 
                   15552: 
                   15553: =cut
                   15554: 
                   15555: sub assign_categories_table {
1.1259    raeburn  15556:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15557:     my $output;
                   15558:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  15559:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15560:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15561:         $maxdepth = scalar(@cats);
                   15562:         if (@cats > 0) {
                   15563:             my $itemcount = 0;
                   15564:             if (ref($cats[0]) eq 'ARRAY') {
                   15565:                 my @currcategories;
                   15566:                 if ($currcat ne '') {
                   15567:                     @currcategories = split('&',$currcat);
                   15568:                 }
1.919     raeburn  15569:                 my $table;
1.663     raeburn  15570:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15571:                     my $parent = $cats[0][$i];
1.919     raeburn  15572:                     next if ($parent eq 'instcode');
                   15573:                     if ($type eq 'Community') {
                   15574:                         next unless ($parent eq 'communities');
1.1239    raeburn  15575:                     } elsif ($type eq 'Placement') {
                   15576:                         next unless ($parent eq 'placement');
1.919     raeburn  15577:                     } else {
1.1239    raeburn  15578:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15579:                     }
1.663     raeburn  15580:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15581:                     my $item = &escape($parent).'::0';
                   15582:                     my $checked = '';
                   15583:                     if (@currcategories > 0) {
                   15584:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15585:                             $checked = ' checked="checked"';
1.663     raeburn  15586:                         }
                   15587:                     }
1.919     raeburn  15588:                     my $parent_title = $parent;
                   15589:                     if ($parent eq 'communities') {
                   15590:                         $parent_title = &mt('Communities');
1.1239    raeburn  15591:                     } elsif ($parent eq 'placement') {
                   15592:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15593:                     }
                   15594:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15595:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15596:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15597:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15598:                     my $depth = 1;
                   15599:                     push(@path,$parent);
1.1259    raeburn  15600:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15601:                     pop(@path);
1.919     raeburn  15602:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15603:                     $itemcount ++;
                   15604:                 }
1.919     raeburn  15605:                 if ($itemcount) {
                   15606:                     $output = &Apache::loncommon::start_data_table().
                   15607:                               $table.
                   15608:                               &Apache::loncommon::end_data_table();
                   15609:                 }
1.663     raeburn  15610:             }
                   15611:         }
                   15612:     }
                   15613:     return $output;
                   15614: }
                   15615: 
                   15616: =pod
                   15617: 
1.1162    raeburn  15618: =item * &assign_category_rows()
1.663     raeburn  15619: 
                   15620: Create a datatable row for display of nested categories in a domain,
                   15621: with checkboxes to allow a course to be categorized,called recursively.
                   15622: 
                   15623: Inputs:
                   15624: 
                   15625: itemcount - track row number for alternating colors
                   15626: 
                   15627: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15628:       categories and subcategories.
                   15629: 
                   15630: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15631: 
                   15632: parent - parent of current category item
                   15633: 
                   15634: path - Array containing all categories back up through the hierarchy from the
                   15635:        current category to the top level.
                   15636: 
                   15637: currcategories - reference to array of current categories assigned to the course
                   15638: 
1.1260    raeburn  15639: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15640:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15641: 
1.663     raeburn  15642: Returns: $output (markup to be displayed).
                   15643: 
                   15644: =cut
                   15645: 
                   15646: sub assign_category_rows {
1.1259    raeburn  15647:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15648:     my ($text,$name,$item,$chgstr);
                   15649:     if (ref($cats) eq 'ARRAY') {
                   15650:         my $maxdepth = scalar(@{$cats});
                   15651:         if (ref($cats->[$depth]) eq 'HASH') {
                   15652:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15653:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15654:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15655:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15656:                 for (my $j=0; $j<$numchildren; $j++) {
                   15657:                     $name = $cats->[$depth]{$parent}[$j];
                   15658:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15659:                     my $deeper = $depth+1;
                   15660:                     my $checked = '';
                   15661:                     if (ref($currcategories) eq 'ARRAY') {
                   15662:                         if (@{$currcategories} > 0) {
                   15663:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15664:                                 $checked = ' checked="checked"';
1.663     raeburn  15665:                             }
                   15666:                         }
                   15667:                     }
1.664     raeburn  15668:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15669:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15670:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15671:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15672:                              '</td><td>';
1.663     raeburn  15673:                     if (ref($path) eq 'ARRAY') {
                   15674:                         push(@{$path},$name);
1.1259    raeburn  15675:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15676:                         pop(@{$path});
                   15677:                     }
                   15678:                     $text .= '</td></tr>';
                   15679:                 }
                   15680:                 $text .= '</table></td>';
                   15681:             }
                   15682:         }
                   15683:     }
                   15684:     return $text;
                   15685: }
                   15686: 
1.1181    raeburn  15687: =pod
                   15688: 
                   15689: =back
                   15690: 
                   15691: =cut
                   15692: 
1.655     raeburn  15693: ############################################################
                   15694: ############################################################
                   15695: 
                   15696: 
1.443     albertel 15697: sub commit_customrole {
1.664     raeburn  15698:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15699:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15700:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15701:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15702:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15703:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15704:                  '</b><br />';
                   15705:     return $output;
                   15706: }
                   15707: 
                   15708: sub commit_standardrole {
1.1116    raeburn  15709:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15710:     my ($output,$logmsg,$linefeed);
                   15711:     if ($context eq 'auto') {
                   15712:         $linefeed = "\n";
                   15713:     } else {
                   15714:         $linefeed = "<br />\n";
                   15715:     }  
1.443     albertel 15716:     if ($three eq 'st') {
1.541     raeburn  15717:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15718:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15719:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15720:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15721:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15722:         } else {
1.541     raeburn  15723:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15724:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15725:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15726:             if ($context eq 'auto') {
                   15727:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15728:             } else {
                   15729:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15730:                &mt('Add to classlist').': <b>ok</b>';
                   15731:             }
                   15732:             $output .= $linefeed;
1.443     albertel 15733:         }
                   15734:     } else {
                   15735:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15736:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15737:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15738:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15739:         if ($context eq 'auto') {
                   15740:             $output .= $result.$linefeed;
                   15741:         } else {
                   15742:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15743:         }
1.443     albertel 15744:     }
                   15745:     return $output;
                   15746: }
                   15747: 
                   15748: sub commit_studentrole {
1.1116    raeburn  15749:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15750:         $credits) = @_;
1.626     raeburn  15751:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15752:     if ($context eq 'auto') {
                   15753:         $linefeed = "\n";
                   15754:     } else {
                   15755:         $linefeed = '<br />'."\n";
                   15756:     }
1.443     albertel 15757:     if (defined($one) && defined($two)) {
                   15758:         my $cid=$one.'_'.$two;
                   15759:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15760:         my $secchange = 0;
                   15761:         my $expire_role_result;
                   15762:         my $modify_section_result;
1.628     raeburn  15763:         if ($oldsec ne '-1') { 
                   15764:             if ($oldsec ne $sec) {
1.443     albertel 15765:                 $secchange = 1;
1.628     raeburn  15766:                 my $now = time;
1.443     albertel 15767:                 my $uurl='/'.$cid;
                   15768:                 $uurl=~s/\_/\//g;
                   15769:                 if ($oldsec) {
                   15770:                     $uurl.='/'.$oldsec;
                   15771:                 }
1.626     raeburn  15772:                 $oldsecurl = $uurl;
1.628     raeburn  15773:                 $expire_role_result = 
1.652     raeburn  15774:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15775:                 if ($env{'request.course.sec'} ne '') { 
                   15776:                     if ($expire_role_result eq 'refused') {
                   15777:                         my @roles = ('st');
                   15778:                         my @statuses = ('previous');
                   15779:                         my @roledoms = ($one);
                   15780:                         my $withsec = 1;
                   15781:                         my %roleshash = 
                   15782:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15783:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15784:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15785:                             my ($oldstart,$oldend) = 
                   15786:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15787:                             if ($oldend > 0 && $oldend <= $now) {
                   15788:                                 $expire_role_result = 'ok';
                   15789:                             }
                   15790:                         }
                   15791:                     }
                   15792:                 }
1.443     albertel 15793:                 $result = $expire_role_result;
                   15794:             }
                   15795:         }
                   15796:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15797:             $modify_section_result = 
                   15798:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15799:                                                            undef,undef,undef,$sec,
                   15800:                                                            $end,$start,'','',$cid,
                   15801:                                                            '',$context,$credits);
1.443     albertel 15802:             if ($modify_section_result =~ /^ok/) {
                   15803:                 if ($secchange == 1) {
1.628     raeburn  15804:                     if ($sec eq '') {
                   15805:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15806:                     } else {
                   15807:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15808:                     }
1.443     albertel 15809:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15810:                     if ($sec eq '') {
                   15811:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15812:                     } else {
                   15813:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15814:                     }
1.443     albertel 15815:                 } else {
1.628     raeburn  15816:                     if ($sec eq '') {
                   15817:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15818:                     } else {
                   15819:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15820:                     }
1.443     albertel 15821:                 }
                   15822:             } else {
1.1115    raeburn  15823:                 if ($secchange) { 
1.628     raeburn  15824:                     $$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;
                   15825:                 } else {
                   15826:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15827:                 }
1.443     albertel 15828:             }
                   15829:             $result = $modify_section_result;
                   15830:         } elsif ($secchange == 1) {
1.628     raeburn  15831:             if ($oldsec eq '') {
1.1103    raeburn  15832:                 $$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  15833:             } else {
                   15834:                 $$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;
                   15835:             }
1.626     raeburn  15836:             if ($expire_role_result eq 'refused') {
                   15837:                 my $newsecurl = '/'.$cid;
                   15838:                 $newsecurl =~ s/\_/\//g;
                   15839:                 if ($sec ne '') {
                   15840:                     $newsecurl.='/'.$sec;
                   15841:                 }
                   15842:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15843:                     if ($sec eq '') {
                   15844:                         $$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;
                   15845:                     } else {
                   15846:                         $$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;
                   15847:                     }
                   15848:                 }
                   15849:             }
1.443     albertel 15850:         }
                   15851:     } else {
1.626     raeburn  15852:         $$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 15853:         $result = "error: incomplete course id\n";
                   15854:     }
                   15855:     return $result;
                   15856: }
                   15857: 
1.1108    raeburn  15858: sub show_role_extent {
                   15859:     my ($scope,$context,$role) = @_;
                   15860:     $scope =~ s{^/}{};
                   15861:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15862:     push(@courseroles,'co');
                   15863:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15864:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15865:         $scope =~ s{/}{_};
                   15866:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15867:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15868:         my ($audom,$auname) = split(/\//,$scope);
                   15869:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15870:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15871:     } else {
                   15872:         $scope =~ s{/$}{};
                   15873:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15874:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15875:     }
                   15876: }
                   15877: 
1.443     albertel 15878: ############################################################
                   15879: ############################################################
                   15880: 
1.566     albertel 15881: sub check_clone {
1.578     raeburn  15882:     my ($args,$linefeed) = @_;
1.566     albertel 15883:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15884:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15885:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  15886:     my $clonetitle;
                   15887:     my @clonemsg;
1.566     albertel 15888:     my $can_clone = 0;
1.944     raeburn  15889:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15890:     if ($lctype ne 'community') {
                   15891:         $lctype = 'course';
                   15892:     }
1.566     albertel 15893:     if ($clonehome eq 'no_host') {
1.944     raeburn  15894:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  15895:             push(@clonemsg,({
                   15896:                               mt => 'No new community created.',
                   15897:                               args => [],
                   15898:                             },
                   15899:                             {
                   15900:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   15901:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   15902:                             }));
1.908     raeburn  15903:         } else {
1.1344    raeburn  15904:             push(@clonemsg,({
                   15905:                               mt => 'No new course created.',
                   15906:                               args => [],
                   15907:                             },
                   15908:                             {
                   15909:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   15910:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15911:                             }));
                   15912:         }
1.566     albertel 15913:     } else {
                   15914: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  15915:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  15916:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15917:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  15918:                 push(@clonemsg,({
                   15919:                                   mt => 'No new community created.',
                   15920:                                   args => [],
                   15921:                                 },
                   15922:                                 {
                   15923:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   15924:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15925:                                 }));
                   15926:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  15927:             }
                   15928:         }
1.1262    raeburn  15929: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15930:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15931: 	    $can_clone = 1;
                   15932: 	} else {
1.1221    raeburn  15933: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15934: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15935:             if ($clonehash{'cloners'} eq '') {
                   15936:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15937:                 if ($domdefs{'canclone'}) {
                   15938:                     unless ($domdefs{'canclone'} eq 'none') {
                   15939:                         if ($domdefs{'canclone'} eq 'domain') {
                   15940:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15941:                                 $can_clone = 1;
                   15942:                             }
                   15943:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15944:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15945:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15946:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15947:                                 $can_clone = 1;
                   15948:                             }
                   15949:                         }
                   15950:                     }
                   15951:                 }
1.578     raeburn  15952:             } else {
1.1221    raeburn  15953: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15954:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15955:                     $can_clone = 1;
1.1221    raeburn  15956:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15957:                     $can_clone = 1;
1.1225    raeburn  15958:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15959:                     $can_clone = 1;
1.1221    raeburn  15960:                 }
                   15961:                 unless ($can_clone) {
1.1225    raeburn  15962:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15963:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15964:                         my (%gotdomdefaults,%gotcodedefaults);
                   15965:                         foreach my $cloner (@cloners) {
                   15966:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15967:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15968:                                 my (%codedefaults,@code_order);
                   15969:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15970:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15971:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15972:                                     }
                   15973:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15974:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15975:                                     }
                   15976:                                 } else {
                   15977:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15978:                                                                             \%codedefaults,
                   15979:                                                                             \@code_order);
                   15980:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15981:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15982:                                 }
                   15983:                                 if (@code_order > 0) {
                   15984:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15985:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15986:                                                                                 $args->{'crscode'})) {
                   15987:                                         $can_clone = 1;
                   15988:                                         last;
                   15989:                                     }
                   15990:                                 }
                   15991:                             }
                   15992:                         }
                   15993:                     }
1.1225    raeburn  15994:                 }
                   15995:             }
                   15996:             unless ($can_clone) {
                   15997:                 my $ccrole = 'cc';
                   15998:                 if ($args->{'crstype'} eq 'Community') {
                   15999:                     $ccrole = 'co';
                   16000:                 }
                   16001: 	        my %roleshash =
                   16002: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16003: 					          $args->{'ccdomain'},
                   16004:                                                   'userroles',['active'],[$ccrole],
                   16005: 					          [$args->{'clonedomain'}]);
                   16006: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16007:                     $can_clone = 1;
                   16008:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16009:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16010:                     $can_clone = 1;
1.1221    raeburn  16011:                 }
                   16012:             }
                   16013:             unless ($can_clone) {
                   16014:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16015:                     push(@clonemsg,({
                   16016:                                       mt => 'No new community created.',
                   16017:                                       args => [],
                   16018:                                     },
                   16019:                                     {
                   16020:                                       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]).',
                   16021:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16022:                                     }));
1.942     raeburn  16023:                 } else {
1.1344    raeburn  16024:                     push(@clonemsg,({
                   16025:                                       mt => 'No new course created.',
                   16026:                                       args => [],
                   16027:                                     },
                   16028:                                     {
                   16029:                                       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]).',
                   16030:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16031:                                     }));
1.1221    raeburn  16032:                 }
1.566     albertel 16033: 	    }
1.578     raeburn  16034:         }
1.566     albertel 16035:     }
1.1344    raeburn  16036:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16037: }
                   16038: 
1.444     albertel 16039: sub construct_course {
1.1262    raeburn  16040:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16041:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16042:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16043:     my $linefeed =  '<br />'."\n";
                   16044:     if ($context eq 'auto') {
                   16045:         $linefeed = "\n";
                   16046:     }
1.566     albertel 16047: 
                   16048: #
                   16049: # Are we cloning?
                   16050: #
1.1344    raeburn  16051:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16052:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16053: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16054:         if (!$can_clone) {
1.1344    raeburn  16055: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16056: 	}
                   16057:     }
                   16058: 
1.444     albertel 16059: #
                   16060: # Open course
                   16061: #
1.1239    raeburn  16062:     my $showncrstype;
                   16063:     if ($args->{'crstype'} eq 'Placement') {
                   16064:         $showncrstype = 'placement test'; 
                   16065:     } else {  
                   16066:         $showncrstype = lc($args->{'crstype'});
                   16067:     }
1.444     albertel 16068:     my %cenv=();
                   16069:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16070:                                              $args->{'cdescr'},
                   16071:                                              $args->{'curl'},
                   16072:                                              $args->{'course_home'},
                   16073:                                              $args->{'nonstandard'},
                   16074:                                              $args->{'crscode'},
                   16075:                                              $args->{'ccuname'}.':'.
                   16076:                                              $args->{'ccdomain'},
1.882     raeburn  16077:                                              $args->{'crstype'},
1.1344    raeburn  16078:                                              $cnum,$context,$category,
                   16079:                                              $callercontext);
1.444     albertel 16080: 
                   16081:     # Note: The testing routines depend on this being output; see 
                   16082:     # Utils::Course. This needs to at least be output as a comment
                   16083:     # if anyone ever decides to not show this, and Utils::Course::new
                   16084:     # will need to be suitably modified.
1.1344    raeburn  16085:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16086:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16087:     } else {
                   16088:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16089:     }
1.943     raeburn  16090:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16091:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16092:     }
                   16093: 
1.444     albertel 16094: #
                   16095: # Check if created correctly
                   16096: #
1.479     albertel 16097:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16098:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16099:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16100:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16101:             $outcome .= &mt_user($user_lh,
                   16102:                             'Course creation failed, unrecognized course home server.');
                   16103:         } else {
                   16104:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16105:         }
                   16106:         $outcome .= $linefeed;
                   16107:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16108:     }
1.541     raeburn  16109:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16110: 
1.444     albertel 16111: #
1.566     albertel 16112: # Do the cloning
                   16113: #   
1.1344    raeburn  16114:     my @clonemsg;
1.566     albertel 16115:     if ($can_clone && $cloneid) {
1.1344    raeburn  16116:         push(@clonemsg,
                   16117:                       {
                   16118:                           mt => 'Created [_1] by cloning from [_2]',
                   16119:                           args => [$showncrstype,$clonetitle],
                   16120:                       });
1.566     albertel 16121: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16122: # Copy all files
1.1344    raeburn  16123:         my @info =
                   16124: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16125: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16126:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16127:                                                      $args->{'tinyurls'});
                   16128:         if (@info) {
                   16129:             push(@clonemsg,@info);
                   16130:         }
1.444     albertel 16131: # Restore URL
1.566     albertel 16132: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16133: # Restore title
1.566     albertel 16134: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16135: # Restore creation date, creator and creation context.
                   16136:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16137:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16138:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16139: # Mark as cloned
1.566     albertel 16140: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16141: # Need to clone grading mode
                   16142:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16143:         $cenv{'grading'}=$newenv{'grading'};
                   16144: # Do not clone these environment entries
                   16145:         &Apache::lonnet::del('environment',
                   16146:                   ['default_enrollment_start_date',
                   16147:                    'default_enrollment_end_date',
                   16148:                    'question.email',
                   16149:                    'policy.email',
                   16150:                    'comment.email',
                   16151:                    'pch.users.denied',
1.725     raeburn  16152:                    'plc.users.denied',
                   16153:                    'hidefromcat',
1.1121    raeburn  16154:                    'checkforpriv',
1.1166    raeburn  16155:                    'categories',
                   16156:                    'internal.uniquecode'],
1.638     www      16157:                    $$crsudom,$$crsunum);
1.1170    raeburn  16158:         if ($args->{'textbook'}) {
                   16159:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16160:         }
1.444     albertel 16161:     }
1.566     albertel 16162: 
1.444     albertel 16163: #
                   16164: # Set environment (will override cloned, if existing)
                   16165: #
                   16166:     my @sections = ();
                   16167:     my @xlists = ();
                   16168:     if ($args->{'crstype'}) {
                   16169:         $cenv{'type'}=$args->{'crstype'};
                   16170:     }
                   16171:     if ($args->{'crsid'}) {
                   16172:         $cenv{'courseid'}=$args->{'crsid'};
                   16173:     }
                   16174:     if ($args->{'crscode'}) {
                   16175:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16176:     }
                   16177:     if ($args->{'crsquota'} ne '') {
                   16178:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16179:     } else {
                   16180:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16181:     }
                   16182:     if ($args->{'ccuname'}) {
                   16183:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16184:                                         ':'.$args->{'ccdomain'};
                   16185:     } else {
                   16186:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16187:     }
1.1116    raeburn  16188:     if ($args->{'defaultcredits'}) {
                   16189:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16190:     }
1.444     albertel 16191:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16192:     if ($args->{'crssections'}) {
                   16193:         $cenv{'internal.sectionnums'} = '';
                   16194:         if ($args->{'crssections'} =~ m/,/) {
                   16195:             @sections = split/,/,$args->{'crssections'};
                   16196:         } else {
                   16197:             $sections[0] = $args->{'crssections'};
                   16198:         }
                   16199:         if (@sections > 0) {
                   16200:             foreach my $item (@sections) {
                   16201:                 my ($sec,$gp) = split/:/,$item;
                   16202:                 my $class = $args->{'crscode'}.$sec;
                   16203:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16204:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16205:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16206:                     push(@badclasses,$class);
1.444     albertel 16207:                 }
                   16208:             }
                   16209:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16210:         }
                   16211:     }
                   16212: # do not hide course coordinator from staff listing, 
                   16213: # even if privileged
                   16214:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16215: # add course coordinator's domain to domains to check for privileged users
                   16216: # if different to course domain
                   16217:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16218:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16219:     }
1.444     albertel 16220: # add crosslistings
                   16221:     if ($args->{'crsxlist'}) {
                   16222:         $cenv{'internal.crosslistings'}='';
                   16223:         if ($args->{'crsxlist'} =~ m/,/) {
                   16224:             @xlists = split/,/,$args->{'crsxlist'};
                   16225:         } else {
                   16226:             $xlists[0] = $args->{'crsxlist'};
                   16227:         }
                   16228:         if (@xlists > 0) {
                   16229:             foreach my $item (@xlists) {
                   16230:                 my ($xl,$gp) = split/:/,$item;
                   16231:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16232:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16233:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16234:                     push(@badclasses,$xl);
1.444     albertel 16235:                 }
                   16236:             }
                   16237:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16238:         }
                   16239:     }
                   16240:     if ($args->{'autoadds'}) {
                   16241:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16242:     }
                   16243:     if ($args->{'autodrops'}) {
                   16244:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16245:     }
                   16246: # check for notification of enrollment changes
                   16247:     my @notified = ();
                   16248:     if ($args->{'notify_owner'}) {
                   16249:         if ($args->{'ccuname'} ne '') {
                   16250:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16251:         }
                   16252:     }
                   16253:     if ($args->{'notify_dc'}) {
                   16254:         if ($uname ne '') { 
1.630     raeburn  16255:             push(@notified,$uname.':'.$udom);
1.444     albertel 16256:         }
                   16257:     }
                   16258:     if (@notified > 0) {
                   16259:         my $notifylist;
                   16260:         if (@notified > 1) {
                   16261:             $notifylist = join(',',@notified);
                   16262:         } else {
                   16263:             $notifylist = $notified[0];
                   16264:         }
                   16265:         $cenv{'internal.notifylist'} = $notifylist;
                   16266:     }
                   16267:     if (@badclasses > 0) {
                   16268:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16269:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16270:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16271:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16272:         );
1.1264    raeburn  16273:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16274:                            &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  16275:         if ($context eq 'auto') {
                   16276:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16277:         } else {
1.566     albertel 16278:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16279:         }
                   16280:         foreach my $item (@badclasses) {
1.541     raeburn  16281:             if ($context eq 'auto') {
1.1261    raeburn  16282:                 $outcome .= " - $item\n";
1.541     raeburn  16283:             } else {
1.1261    raeburn  16284:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16285:             }
1.1261    raeburn  16286:         }
                   16287:         if ($context eq 'auto') {
                   16288:             $outcome .= $linefeed;
                   16289:         } else {
                   16290:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16291:         } 
1.444     albertel 16292:     }
                   16293:     if ($args->{'no_end_date'}) {
                   16294:         $args->{'endaccess'} = 0;
                   16295:     }
                   16296:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16297:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16298:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16299:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16300:     if ($args->{'showphotos'}) {
                   16301:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16302:     }
                   16303:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16304:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16305:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16306:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16307:             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'); 
                   16308:             if ($context eq 'auto') {
                   16309:                 $outcome .= $krb_msg;
                   16310:             } else {
1.566     albertel 16311:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16312:             }
                   16313:             $outcome .= $linefeed;
1.444     albertel 16314:         }
                   16315:     }
                   16316:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16317:        if ($args->{'setpolicy'}) {
                   16318:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16319:        }
                   16320:        if ($args->{'setcontent'}) {
                   16321:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16322:        }
1.1251    raeburn  16323:        if ($args->{'setcomment'}) {
                   16324:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16325:        }
1.444     albertel 16326:     }
                   16327:     if ($args->{'reshome'}) {
                   16328: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16329: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16330:     }
                   16331: #
                   16332: # course has keyed access
                   16333: #
                   16334:     if ($args->{'setkeys'}) {
                   16335:        $cenv{'keyaccess'}='yes';
                   16336:     }
                   16337: # if specified, key authority is not course, but user
                   16338: # only active if keyaccess is yes
                   16339:     if ($args->{'keyauth'}) {
1.487     albertel 16340: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16341: 	$user = &LONCAPA::clean_username($user);
                   16342: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16343: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16344: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16345: 	}
                   16346:     }
                   16347: 
1.1166    raeburn  16348: #
1.1167    raeburn  16349: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16350: #
                   16351:     if ($args->{'uniquecode'}) {
                   16352:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16353:         if ($code) {
                   16354:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16355:             my %crsinfo =
                   16356:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16357:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16358:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16359:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16360:             } 
1.1166    raeburn  16361:             if (ref($coderef)) {
                   16362:                 $$coderef = $code;
                   16363:             }
                   16364:         }
                   16365:     }
                   16366: 
1.444     albertel 16367:     if ($args->{'disresdis'}) {
                   16368:         $cenv{'pch.roles.denied'}='st';
                   16369:     }
                   16370:     if ($args->{'disablechat'}) {
                   16371:         $cenv{'plc.roles.denied'}='st';
                   16372:     }
                   16373: 
                   16374:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16375:     # course
                   16376:     $cenv{'course.helper.not.run'} = 1;
                   16377:     #
                   16378:     # Use new Randomseed
                   16379:     #
                   16380:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16381:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16382:     #
                   16383:     # The encryption code and receipt prefix for this course
                   16384:     #
                   16385:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16386:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16387:     #
                   16388:     # By default, use standard grading
                   16389:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16390: 
1.541     raeburn  16391:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16392:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16393: #
                   16394: # Open all assignments
                   16395: #
                   16396:     if ($args->{'openall'}) {
1.1341    raeburn  16397:        my $opendate = time;
                   16398:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16399:            $opendate = $args->{'openallfrom'};
                   16400:        }
1.444     albertel 16401:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16402:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16403:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16404:        $outcome .= &mt('All assignments open starting [_1]',
                   16405:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16406:                    &Apache::lonnet::cput
                   16407:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16408:    }
                   16409: #
                   16410: # Set first page
                   16411: #
                   16412:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16413: 	    || ($cloneid)) {
1.445     albertel 16414: 	use LONCAPA::map;
1.444     albertel 16415: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16416: 
                   16417: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16418:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16419: 
1.444     albertel 16420:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16421:         my $title; my $url;
                   16422:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16423: 	    $title=&mt('Syllabus');
1.444     albertel 16424:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16425:         } else {
1.963     raeburn  16426:             $title=&mt('Table of Contents');
1.444     albertel 16427:             $url='/adm/navmaps';
                   16428:         }
1.445     albertel 16429: 
                   16430:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16431: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16432: 
                   16433: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16434:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16435:     }
1.566     albertel 16436: 
1.1237    raeburn  16437: # 
                   16438: # Set params for Placement Tests
                   16439: #
1.1239    raeburn  16440:     if ($args->{'crstype'} eq 'Placement') {
                   16441:        my %storecontent; 
                   16442:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16443:        my %defaults = (
                   16444:                         buttonshide   => { value => 'yes',
                   16445:                                            type => 'string_yesno',},
                   16446:                         type          => { value => 'randomizetry',
                   16447:                                            type  => 'string_questiontype',},
                   16448:                         maxtries      => { value => 1,
                   16449:                                            type => 'int_pos',},
                   16450:                         problemstatus => { value => 'no',
                   16451:                                            type  => 'string_problemstatus',},
                   16452:                       );
                   16453:        foreach my $key (keys(%defaults)) {
                   16454:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16455:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16456:        }
1.1237    raeburn  16457:        &Apache::lonnet::cput
                   16458:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16459:     }
                   16460: 
1.1344    raeburn  16461:     return (1,$outcome,\@clonemsg);
1.444     albertel 16462: }
                   16463: 
1.1166    raeburn  16464: sub make_unique_code {
                   16465:     my ($cdom,$cnum) = @_;
                   16466:     # get lock on uniquecodes db
                   16467:     my $lockhash = {
                   16468:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16469:                                                   ':'.$env{'user.domain'},
                   16470:                    };
                   16471:     my $tries = 0;
                   16472:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16473:     my ($code,$error);
                   16474:   
                   16475:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16476:         $tries ++;
                   16477:         sleep 1;
                   16478:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16479:     }
                   16480:     if ($gotlock eq 'ok') {
                   16481:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16482:         my $gotcode;
                   16483:         my $attempts = 0;
                   16484:         while ((!$gotcode) && ($attempts < 100)) {
                   16485:             $code = &generate_code();
                   16486:             if (!exists($currcodes{$code})) {
                   16487:                 $gotcode = 1;
                   16488:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16489:                     $error = 'nostore';
                   16490:                 }
                   16491:             }
                   16492:             $attempts ++;
                   16493:         }
                   16494:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16495:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16496:     } else {
                   16497:         $error = 'nolock';
                   16498:     }
                   16499:     return ($code,$error);
                   16500: }
                   16501: 
                   16502: sub generate_code {
                   16503:     my $code;
                   16504:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16505:     for (my $i=0; $i<6; $i++) {
                   16506:         my $lettnum = int (rand 2);
                   16507:         my $item = '';
                   16508:         if ($lettnum) {
                   16509:             $item = $letts[int( rand(18) )];
                   16510:         } else {
                   16511:             $item = 1+int( rand(8) );
                   16512:         }
                   16513:         $code .= $item;
                   16514:     }
                   16515:     return $code;
                   16516: }
                   16517: 
1.444     albertel 16518: ############################################################
                   16519: ############################################################
                   16520: 
1.1237    raeburn  16521: # Community, Course and Placement Test
1.378     raeburn  16522: sub course_type {
                   16523:     my ($cid) = @_;
                   16524:     if (!defined($cid)) {
                   16525:         $cid = $env{'request.course.id'};
                   16526:     }
1.404     albertel 16527:     if (defined($env{'course.'.$cid.'.type'})) {
                   16528:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16529:     } else {
                   16530:         return 'Course';
1.377     raeburn  16531:     }
                   16532: }
1.156     albertel 16533: 
1.406     raeburn  16534: sub group_term {
                   16535:     my $crstype = &course_type();
                   16536:     my %names = (
                   16537:                   'Course' => 'group',
1.865     raeburn  16538:                   'Community' => 'group',
1.1237    raeburn  16539:                   'Placement' => 'group',
1.406     raeburn  16540:                 );
                   16541:     return $names{$crstype};
                   16542: }
                   16543: 
1.902     raeburn  16544: sub course_types {
1.1310    raeburn  16545:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16546:     my %typename = (
                   16547:                          official   => 'Official course',
                   16548:                          unofficial => 'Unofficial course',
                   16549:                          community  => 'Community',
1.1165    raeburn  16550:                          textbook   => 'Textbook course',
1.1237    raeburn  16551:                          placement  => 'Placement test',
1.1310    raeburn  16552:                          lti        => 'LTI provider',
1.902     raeburn  16553:                    );
                   16554:     return (\@types,\%typename);
                   16555: }
                   16556: 
1.156     albertel 16557: sub icon {
                   16558:     my ($file)=@_;
1.505     albertel 16559:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16560:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16561:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16562:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16563: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16564: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16565: 	            $curfext.".gif") {
                   16566: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16567: 		$curfext.".gif";
                   16568: 	}
                   16569:     }
1.249     albertel 16570:     return &lonhttpdurl($iconname);
1.154     albertel 16571: } 
1.84      albertel 16572: 
1.575     albertel 16573: sub lonhttpdurl {
1.692     www      16574: #
                   16575: # Had been used for "small fry" static images on separate port 8080.
                   16576: # Modify here if lightweight http functionality desired again.
                   16577: # Currently eliminated due to increasing firewall issues.
                   16578: #
1.575     albertel 16579:     my ($url)=@_;
1.692     www      16580:     return $url;
1.215     albertel 16581: }
                   16582: 
1.213     albertel 16583: sub connection_aborted {
                   16584:     my ($r)=@_;
                   16585:     $r->print(" ");$r->rflush();
                   16586:     my $c = $r->connection;
                   16587:     return $c->aborted();
                   16588: }
                   16589: 
1.221     foxr     16590: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16591: #    strings as 'strings'.
                   16592: sub escape_single {
1.221     foxr     16593:     my ($input) = @_;
1.223     albertel 16594:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16595:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16596:     return $input;
                   16597: }
1.223     albertel 16598: 
1.222     foxr     16599: #  Same as escape_single, but escape's "'s  This 
                   16600: #  can be used for  "strings"
                   16601: sub escape_double {
                   16602:     my ($input) = @_;
                   16603:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16604:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16605:     return $input;
                   16606: }
1.223     albertel 16607:  
1.222     foxr     16608: #   Escapes the last element of a full URL.
                   16609: sub escape_url {
                   16610:     my ($url)   = @_;
1.238     raeburn  16611:     my @urlslices = split(/\//, $url,-1);
1.369     www      16612:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16613:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16614: }
1.462     albertel 16615: 
1.820     raeburn  16616: sub compare_arrays {
                   16617:     my ($arrayref1,$arrayref2) = @_;
                   16618:     my (@difference,%count);
                   16619:     @difference = ();
                   16620:     %count = ();
                   16621:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16622:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16623:         foreach my $element (keys(%count)) {
                   16624:             if ($count{$element} == 1) {
                   16625:                 push(@difference,$element);
                   16626:             }
                   16627:         }
                   16628:     }
                   16629:     return @difference;
                   16630: }
                   16631: 
1.1322    raeburn  16632: sub lon_status_items {
                   16633:     my %defaults = (
                   16634:                      E         => 100,
                   16635:                      W         => 4,
                   16636:                      N         => 1,
1.1324    raeburn  16637:                      U         => 5,
1.1322    raeburn  16638:                      threshold => 200,
                   16639:                      sysmail   => 2500,
                   16640:                    );
                   16641:     my %names = (
                   16642:                    E => 'Errors',
                   16643:                    W => 'Warnings',
                   16644:                    N => 'Notices',
1.1324    raeburn  16645:                    U => 'Unsent',
1.1322    raeburn  16646:                 );
                   16647:     return (\%defaults,\%names);
                   16648: }
                   16649: 
1.817     bisitz   16650: # -------------------------------------------------------- Initialize user login
1.462     albertel 16651: sub init_user_environment {
1.463     albertel 16652:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16653:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16654: 
                   16655:     my $public=($username eq 'public' && $domain eq 'public');
                   16656: 
1.1062    raeburn  16657:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16658:     my $now=time;
                   16659: 
                   16660:     if ($public) {
                   16661: 	my $max_public=100;
                   16662: 	my $oldest;
                   16663: 	my $oldest_time=0;
                   16664: 	for(my $next=1;$next<=$max_public;$next++) {
                   16665: 	    if (-e $lonids."/publicuser_$next.id") {
                   16666: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16667: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16668: 		    $oldest_time=$mtime;
                   16669: 		    $oldest=$next;
                   16670: 		}
                   16671: 	    } else {
                   16672: 		$cookie="publicuser_$next";
                   16673: 		last;
                   16674: 	    }
                   16675: 	}
                   16676: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16677:     } else {
1.1275    raeburn  16678: 	# See if old ID present, if so, remove if this isn't a robot,
                   16679: 	# killing any existing non-robot sessions
1.463     albertel 16680: 	if (!$args->{'robot'}) {
                   16681: 	    opendir(DIR,$lonids);
                   16682: 	    while ($filename=readdir(DIR)) {
                   16683: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  16684:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16685:                             &GDBM_READER(),0640)) {
1.1295    raeburn  16686:                         my $linkedfile;
1.1320    raeburn  16687:                         if (exists($oldenv{'user.linkedenv'})) {
                   16688:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  16689:                         }
1.1320    raeburn  16690:                         untie(%oldenv);
                   16691:                         if (unlink("$lonids/$filename")) {
                   16692:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16693:                                 if (-l "$lonids/$linkedfile.id") {
                   16694:                                     unlink("$lonids/$linkedfile.id");
                   16695:                                 }
1.1295    raeburn  16696:                             }
                   16697:                         }
                   16698:                     } else {
                   16699:                         unlink($lonids.'/'.$filename);
                   16700:                     }
1.463     albertel 16701: 		}
1.462     albertel 16702: 	    }
1.463     albertel 16703: 	    closedir(DIR);
1.1204    raeburn  16704: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16705:             my $namespace = 'nohist_courseeditor';
                   16706:             my $lockingkey = 'paste'."\0".'locked_num';
                   16707:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16708:                                                 $domain,$username);
                   16709:             if (exists($lockhash{$lockingkey})) {
                   16710:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16711:                 unless ($delresult eq 'ok') {
                   16712:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16713:                 }
                   16714:             }
1.462     albertel 16715: 	}
                   16716: # Give them a new cookie
1.463     albertel 16717: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16718: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16719: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16720:     
                   16721: # Initialize roles
                   16722: 
1.1062    raeburn  16723: 	($userroles,$firstaccenv,$timerintenv) = 
                   16724:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16725:     }
                   16726: # ------------------------------------ Check browser type and MathML capability
                   16727: 
1.1194    raeburn  16728:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16729:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16730: 
                   16731: # ------------------------------------------------------------- Get environment
                   16732: 
                   16733:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16734:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16735:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16736: 	undef(%userenv);
                   16737:     }
                   16738:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16739: 	$form->{'interface'}=$userenv{'interface'};
                   16740:     }
                   16741:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16742: 
                   16743: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16744:     foreach my $option ('interface','localpath','localres') {
                   16745:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16746:     }
                   16747: # --------------------------------------------------------- Write first profile
                   16748: 
                   16749:     {
                   16750: 	my %initial_env = 
                   16751: 	    ("user.name"          => $username,
                   16752: 	     "user.domain"        => $domain,
                   16753: 	     "user.home"          => $authhost,
                   16754: 	     "browser.type"       => $clientbrowser,
                   16755: 	     "browser.version"    => $clientversion,
                   16756: 	     "browser.mathml"     => $clientmathml,
                   16757: 	     "browser.unicode"    => $clientunicode,
                   16758: 	     "browser.os"         => $clientos,
1.1137    raeburn  16759:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16760:              "browser.info"       => $clientinfo,
1.1194    raeburn  16761:              "browser.osversion"  => $clientosversion,
1.462     albertel 16762: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16763: 	     "request.course.fn"  => '',
                   16764: 	     "request.course.uri" => '',
                   16765: 	     "request.course.sec" => '',
                   16766: 	     "request.role"       => 'cm',
                   16767: 	     "request.role.adv"   => $env{'user.adv'},
                   16768: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16769: 
                   16770:         if ($form->{'localpath'}) {
                   16771: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16772: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16773:         }
                   16774: 	
                   16775: 	if ($form->{'interface'}) {
                   16776: 	    $form->{'interface'}=~s/\W//gs;
                   16777: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16778: 	    $env{'browser.interface'}=$form->{'interface'};
                   16779: 	}
                   16780: 
1.1157    raeburn  16781:         if ($form->{'iptoken'}) {
                   16782:             my $lonhost = $r->dir_config('lonHostID');
                   16783:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16784:             $env{'user.noloadbalance'} = $lonhost;
                   16785:         }
                   16786: 
1.1268    raeburn  16787:         if ($form->{'noloadbalance'}) {
                   16788:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16789:             my $hosthere = $form->{'noloadbalance'};
                   16790:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16791:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16792:                 $env{'user.noloadbalance'} = $hosthere;
                   16793:             }
                   16794:         }
                   16795: 
1.1016    raeburn  16796:         unless ($domain eq 'public') {
1.1273    raeburn  16797:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16798:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16799: 
                   16800:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16801:                 $userenv{'availabletools.'.$tool} = 
                   16802:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16803:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16804:             }
1.980     raeburn  16805: 
1.1311    raeburn  16806:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  16807:                 $userenv{'canrequest.'.$crstype} =
                   16808:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16809:                                                       'reload','requestcourses',
                   16810:                                                       \%userenv,\%domdef,\%is_adv);
                   16811:             }
1.724     raeburn  16812: 
1.1273    raeburn  16813:             $userenv{'canrequest.author'} =
                   16814:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16815:                                                   'reload','requestauthor',
1.980     raeburn  16816:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16817:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16818:                                                  $domain,$username);
                   16819:             my $reqstatus = $reqauthor{'author_status'};
                   16820:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16821:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16822:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16823:                                                       $reqauthor{'author'}{'timestamp'};
                   16824:                 }
1.1092    raeburn  16825:             }
1.1287    raeburn  16826:             my ($types,$typename) = &course_types();
                   16827:             if (ref($types) eq 'ARRAY') {
                   16828:                 my @options = ('approval','validate','autolimit');
                   16829:                 my $optregex = join('|',@options);
                   16830:                 my (%willtrust,%trustchecked);
                   16831:                 foreach my $type (@{$types}) {
                   16832:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   16833:                     if ($dom_str ne '') {
                   16834:                         my $updatedstr = '';
                   16835:                         my @possdomains = split(',',$dom_str);
                   16836:                         foreach my $entry (@possdomains) {
                   16837:                             my ($extdom,$extopt) = split(':',$entry);
                   16838:                             unless ($trustchecked{$extdom}) {
                   16839:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   16840:                                 $trustchecked{$extdom} = 1;
                   16841:                             }
                   16842:                             if ($willtrust{$extdom}) {
                   16843:                                 $updatedstr .= $entry.',';
                   16844:                             }
                   16845:                         }
                   16846:                         $updatedstr =~ s/,$//;
                   16847:                         if ($updatedstr) {
                   16848:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   16849:                         } else {
                   16850:                             delete($userenv{'reqcrsotherdom.'.$type});
                   16851:                         }
                   16852:                     }
                   16853:                 }
                   16854:             }
1.1092    raeburn  16855:         }
1.462     albertel 16856: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16857: 
1.462     albertel 16858: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16859: 		 &GDBM_WRCREAT(),0640)) {
                   16860: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16861: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16862: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16863:             if (ref($firstaccenv) eq 'HASH') {
                   16864:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16865:             }
                   16866:             if (ref($timerintenv) eq 'HASH') {
                   16867:                 &_add_to_env(\%disk_env,$timerintenv);
                   16868:             }
1.463     albertel 16869: 	    if (ref($args->{'extra_env'})) {
                   16870: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16871: 	    }
1.462     albertel 16872: 	    untie(%disk_env);
                   16873: 	} else {
1.705     tempelho 16874: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16875: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16876: 	    return 'error: '.$!;
                   16877: 	}
                   16878:     }
                   16879:     $env{'request.role'}='cm';
                   16880:     $env{'request.role.adv'}=$env{'user.adv'};
                   16881:     $env{'browser.type'}=$clientbrowser;
                   16882: 
                   16883:     return $cookie;
                   16884: 
                   16885: }
                   16886: 
                   16887: sub _add_to_env {
                   16888:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16889:     if (ref($env_data) eq 'HASH') {
                   16890:         while (my ($key,$value) = each(%$env_data)) {
                   16891: 	    $idf->{$prefix.$key} = $value;
                   16892: 	    $env{$prefix.$key}   = $value;
                   16893:         }
1.462     albertel 16894:     }
                   16895: }
                   16896: 
1.685     tempelho 16897: # --- Get the symbolic name of a problem and the url
                   16898: sub get_symb {
                   16899:     my ($request,$silent) = @_;
1.726     raeburn  16900:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16901:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16902:     if ($symb eq '') {
                   16903:         if (!$silent) {
1.1071    raeburn  16904:             if (ref($request)) { 
                   16905:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16906:             }
1.685     tempelho 16907:             return ();
                   16908:         }
                   16909:     }
                   16910:     &Apache::lonenc::check_decrypt(\$symb);
                   16911:     return ($symb);
                   16912: }
                   16913: 
                   16914: # --------------------------------------------------------------Get annotation
                   16915: 
                   16916: sub get_annotation {
                   16917:     my ($symb,$enc) = @_;
                   16918: 
                   16919:     my $key = $symb;
                   16920:     if (!$enc) {
                   16921:         $key =
                   16922:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16923:     }
                   16924:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16925:     return $annotation{$key};
                   16926: }
                   16927: 
                   16928: sub clean_symb {
1.731     raeburn  16929:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16930: 
                   16931:     &Apache::lonenc::check_decrypt(\$symb);
                   16932:     my $enc = $env{'request.enc'};
1.731     raeburn  16933:     if ($delete_enc) {
1.730     raeburn  16934:         delete($env{'request.enc'});
                   16935:     }
1.685     tempelho 16936: 
                   16937:     return ($symb,$enc);
                   16938: }
1.462     albertel 16939: 
1.1181    raeburn  16940: ############################################################
                   16941: ############################################################
                   16942: 
                   16943: =pod
                   16944: 
                   16945: =head1 Routines for building display used to search for courses
                   16946: 
                   16947: 
                   16948: =over 4
                   16949: 
                   16950: =item * &build_filters()
                   16951: 
                   16952: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16953: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16954: and quotacheck.pl
                   16955: 
1.1181    raeburn  16956: 
                   16957: Inputs:
                   16958: 
                   16959: filterlist - anonymous array of fields to include as potential filters 
                   16960: 
                   16961: crstype - course type
                   16962: 
                   16963: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16964:               to pop-open a course selector (will contain "extra element"). 
                   16965: 
                   16966: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16967: 
                   16968: filter - anonymous hash of criteria and their values
                   16969: 
                   16970: action - form action
                   16971: 
                   16972: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16973: 
1.1182    raeburn  16974: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16975: 
                   16976: cloneruname - username of owner of new course who wants to clone
                   16977: 
                   16978: clonerudom - domain of owner of new course who wants to clone
                   16979: 
                   16980: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16981: 
                   16982: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16983: 
                   16984: codedom - domain
                   16985: 
                   16986: formname - value of form element named "form". 
                   16987: 
                   16988: fixeddom - domain, if fixed.
                   16989: 
                   16990: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16991: 
                   16992: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16993: 
                   16994: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16995: 
                   16996: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16997: 
                   16998: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16999: 
                   17000: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17001: 
                   17002: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17003: 
1.1182    raeburn  17004: 
1.1181    raeburn  17005: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17006: 
1.1182    raeburn  17007: 
1.1181    raeburn  17008: Side Effects: None
                   17009: 
                   17010: =cut
                   17011: 
                   17012: # ---------------------------------------------- search for courses based on last activity etc.
                   17013: 
                   17014: sub build_filters {
                   17015:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17016:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17017:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17018:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17019:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17020:     my ($list,$jscript);
1.1181    raeburn  17021:     my $onchange = 'javascript:updateFilters(this)';
                   17022:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17023:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17024:         $typeselectform,$instcodetitle);
                   17025:     if ($formname eq '') {
                   17026:         $formname = $caller;
                   17027:     }
                   17028:     foreach my $item (@{$filterlist}) {
                   17029:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17030:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17031:             if ($item eq 'domainfilter') {
                   17032:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17033:             } elsif ($item eq 'coursefilter') {
                   17034:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17035:             } elsif ($item eq 'ownerfilter') {
                   17036:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17037:             } elsif ($item eq 'ownerdomfilter') {
                   17038:                 $filter->{'ownerdomfilter'} =
                   17039:                     &LONCAPA::clean_domain($filter->{$item});
                   17040:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17041:                                                        'ownerdomfilter',1);
                   17042:             } elsif ($item eq 'personfilter') {
                   17043:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17044:             } elsif ($item eq 'persondomfilter') {
                   17045:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17046:                                                         'persondomfilter',1);
                   17047:             } else {
                   17048:                 $filter->{$item} =~ s/\W//g;
                   17049:             }
                   17050:             if (!$filter->{$item}) {
                   17051:                 $filter->{$item} = '';
                   17052:             }
                   17053:         }
                   17054:         if ($item eq 'domainfilter') {
                   17055:             my $allow_blank = 1;
                   17056:             if ($formname eq 'portform') {
                   17057:                 $allow_blank=0;
                   17058:             } elsif ($formname eq 'studentform') {
                   17059:                 $allow_blank=0;
                   17060:             }
                   17061:             if ($fixeddom) {
                   17062:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17063:                                     ' value="'.$codedom.'" />'.
                   17064:                                     &Apache::lonnet::domain($codedom,'description');
                   17065:             } else {
                   17066:                 $domainselectform = &select_dom_form($filter->{$item},
                   17067:                                                      'domainfilter',
                   17068:                                                       $allow_blank,'',$onchange);
                   17069:             }
                   17070:         } else {
                   17071:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17072:         }
                   17073:     }
                   17074: 
                   17075:     # last course activity filter and selection
                   17076:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17077: 
                   17078:     # course created filter and selection
                   17079:     if (exists($filter->{'createdfilter'})) {
                   17080:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17081:     }
                   17082: 
1.1239    raeburn  17083:     my $prefix = $crstype;
                   17084:     if ($crstype eq 'Placement') {
                   17085:         $prefix = 'Placement Test'
                   17086:     }
1.1181    raeburn  17087:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17088:                 'cac' => "$prefix Activity",
                   17089:                 'ccr' => "$prefix Created",
                   17090:                 'cde' => "$prefix Title",
                   17091:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17092:                 'ins' => 'Institutional Code',
                   17093:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17094:                 'cow' => "$prefix Owner/Co-owner",
                   17095:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17096:                 'cog' => 'Type',
                   17097:              );
                   17098: 
                   17099:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17100:         my $typeval = 'Course';
                   17101:         if ($crstype eq 'Community') {
                   17102:             $typeval = 'Community';
1.1239    raeburn  17103:         } elsif ($crstype eq 'Placement') {
                   17104:             $typeval = 'Placement';
1.1181    raeburn  17105:         }
                   17106:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17107:     } else {
                   17108:         $typeselectform =  '<select name="type" size="1"';
                   17109:         if ($onchange) {
                   17110:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17111:         }
                   17112:         $typeselectform .= '>'."\n";
1.1237    raeburn  17113:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17114:             my $shown;
                   17115:             if ($posstype eq 'Placement') {
                   17116:                 $shown = &mt('Placement Test');
                   17117:             } else {
                   17118:                 $shown = &mt($posstype);
                   17119:             }
1.1181    raeburn  17120:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17121:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17122:         }
                   17123:         $typeselectform.="</select>";
                   17124:     }
                   17125: 
                   17126:     my ($cloneableonlyform,$cloneabletitle);
                   17127:     if (exists($filter->{'cloneableonly'})) {
                   17128:         my $cloneableon = '';
                   17129:         my $cloneableoff = ' checked="checked"';
                   17130:         if ($filter->{'cloneableonly'}) {
                   17131:             $cloneableon = $cloneableoff;
                   17132:             $cloneableoff = '';
                   17133:         }
                   17134:         $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>';
                   17135:         if ($formname eq 'ccrs') {
1.1187    bisitz   17136:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17137:         } else {
                   17138:             $cloneabletitle = &mt('Cloneable by you');
                   17139:         }
                   17140:     }
                   17141:     my $officialjs;
                   17142:     if ($crstype eq 'Course') {
                   17143:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17144: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17145: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17146:             if ($codedom) { 
1.1181    raeburn  17147:                 $officialjs = 1;
                   17148:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17149:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17150:                                                                   $officialjs,$codetitlesref);
                   17151:                 if ($jscript) {
1.1182    raeburn  17152:                     $jscript = '<script type="text/javascript">'."\n".
                   17153:                                '// <![CDATA['."\n".
                   17154:                                $jscript."\n".
                   17155:                                '// ]]>'."\n".
                   17156:                                '</script>'."\n";
1.1181    raeburn  17157:                 }
                   17158:             }
                   17159:             if ($instcodeform eq '') {
                   17160:                 $instcodeform =
                   17161:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17162:                     $list->{'instcodefilter'}.'" />';
                   17163:                 $instcodetitle = $lt{'ins'};
                   17164:             } else {
                   17165:                 $instcodetitle = $lt{'inc'};
                   17166:             }
                   17167:             if ($fixeddom) {
                   17168:                 $instcodetitle .= '<br />('.$codedom.')';
                   17169:             }
                   17170:         }
                   17171:     }
                   17172:     my $output = qq|
                   17173: <form method="post" name="filterpicker" action="$action">
                   17174: <input type="hidden" name="form" value="$formname" />
                   17175: |;
                   17176:     if ($formname eq 'modifycourse') {
                   17177:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17178:                    '<input type="hidden" name="prevphase" value="'.
                   17179:                    $prevphase.'" />'."\n";
1.1198    musolffc 17180:     } elsif ($formname eq 'quotacheck') {
                   17181:         $output .= qq|
                   17182: <input type="hidden" name="sortby" value="" />
                   17183: <input type="hidden" name="sortorder" value="" />
                   17184: |;
                   17185:     } else {
1.1181    raeburn  17186:         my $name_input;
                   17187:         if ($cnameelement ne '') {
                   17188:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17189:                           $cnameelement.'" />';
                   17190:         }
                   17191:         $output .= qq|
1.1182    raeburn  17192: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17193: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17194: $name_input
                   17195: $roleelement
                   17196: $multelement
                   17197: $typeelement
                   17198: |;
                   17199:         if ($formname eq 'portform') {
                   17200:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17201:         }
                   17202:     }
                   17203:     if ($fixeddom) {
                   17204:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17205:     }
                   17206:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17207:     if ($sincefilterform) {
                   17208:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17209:                   .$sincefilterform
                   17210:                   .&Apache::lonhtmlcommon::row_closure();
                   17211:     }
                   17212:     if ($createdfilterform) {
                   17213:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17214:                   .$createdfilterform
                   17215:                   .&Apache::lonhtmlcommon::row_closure();
                   17216:     }
                   17217:     if ($domainselectform) {
                   17218:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17219:                   .$domainselectform
                   17220:                   .&Apache::lonhtmlcommon::row_closure();
                   17221:     }
                   17222:     if ($typeselectform) {
                   17223:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17224:             $output .= $typeselectform;
                   17225:         } else {
                   17226:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17227:                       .$typeselectform
                   17228:                       .&Apache::lonhtmlcommon::row_closure();
                   17229:         }
                   17230:     }
                   17231:     if ($instcodeform) {
                   17232:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17233:                   .$instcodeform
                   17234:                   .&Apache::lonhtmlcommon::row_closure();
                   17235:     }
                   17236:     if (exists($filter->{'ownerfilter'})) {
                   17237:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17238:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17239:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17240:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17241:                    $ownerdomselectform.'</td></tr></table>'.
                   17242:                    &Apache::lonhtmlcommon::row_closure();
                   17243:     }
                   17244:     if (exists($filter->{'personfilter'})) {
                   17245:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17246:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17247:                    '<input type="text" name="personfilter" size="20" value="'.
                   17248:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17249:                    $persondomselectform.'</td></tr></table>'.
                   17250:                    &Apache::lonhtmlcommon::row_closure();
                   17251:     }
                   17252:     if (exists($filter->{'coursefilter'})) {
                   17253:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17254:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17255:                   .$list->{'coursefilter'}.'" />'
                   17256:                   .&Apache::lonhtmlcommon::row_closure();
                   17257:     }
                   17258:     if ($cloneableonlyform) {
                   17259:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17260:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17261:     }
                   17262:     if (exists($filter->{'descriptfilter'})) {
                   17263:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17264:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17265:                   .$list->{'descriptfilter'}.'" />'
                   17266:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17267:     }
                   17268:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17269:                '<input type="hidden" name="updater" value="" />'."\n".
                   17270:                '<input type="submit" name="gosearch" value="'.
                   17271:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17272:     return $jscript.$clonewarning.$output;
                   17273: }
                   17274: 
                   17275: =pod 
                   17276: 
                   17277: =item * &timebased_select_form()
                   17278: 
1.1182    raeburn  17279: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17280: filter e.g., Course Activity, Course Created, when searching for courses
                   17281: or communities
                   17282: 
                   17283: Inputs:
                   17284: 
                   17285: item - name of form element (sincefilter or createdfilter)
                   17286: 
                   17287: filter - anonymous hash of criteria and their values
                   17288: 
                   17289: Returns: HTML for a select box contained a blank, then six time selections,
                   17290:          with value set in incoming form variables currently selected. 
                   17291: 
                   17292: Side Effects: None
                   17293: 
                   17294: =cut
                   17295: 
                   17296: sub timebased_select_form {
                   17297:     my ($item,$filter) = @_;
                   17298:     if (ref($filter) eq 'HASH') {
                   17299:         $filter->{$item} =~ s/[^\d-]//g;
                   17300:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17301:         return &select_form(
                   17302:                             $filter->{$item},
                   17303:                             $item,
                   17304:                             {      '-1' => '',
                   17305:                                 '86400' => &mt('today'),
                   17306:                                '604800' => &mt('last week'),
                   17307:                               '2592000' => &mt('last month'),
                   17308:                               '7776000' => &mt('last three months'),
                   17309:                              '15552000' => &mt('last six months'),
                   17310:                              '31104000' => &mt('last year'),
                   17311:                     'select_form_order' =>
                   17312:                            ['-1','86400','604800','2592000','7776000',
                   17313:                             '15552000','31104000']});
                   17314:     }
                   17315: }
                   17316: 
                   17317: =pod
                   17318: 
                   17319: =item * &js_changer()
                   17320: 
                   17321: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17322: when course type or domain is changed, and also to hide 'Searching ...' on
                   17323: page load completion for page showing search result.
1.1181    raeburn  17324: 
                   17325: Inputs: None
                   17326: 
1.1183    raeburn  17327: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17328: 
                   17329: Side Effects: None
                   17330: 
                   17331: =cut
                   17332: 
                   17333: sub js_changer {
                   17334:     return <<ENDJS;
                   17335: <script type="text/javascript">
                   17336: // <![CDATA[
                   17337: function updateFilters(caller) {
                   17338:     if (typeof(caller) != "undefined") {
                   17339:         document.filterpicker.updater.value = caller.name;
                   17340:     }
                   17341:     document.filterpicker.submit();
                   17342: }
1.1183    raeburn  17343: 
                   17344: function hideSearching() {
                   17345:     if (document.getElementById('searching')) {
                   17346:         document.getElementById('searching').style.display = 'none';
                   17347:     }
                   17348:     return;
                   17349: }
                   17350: 
1.1181    raeburn  17351: // ]]>
                   17352: </script>
                   17353: 
                   17354: ENDJS
                   17355: }
                   17356: 
                   17357: =pod
                   17358: 
1.1182    raeburn  17359: =item * &search_courses()
                   17360: 
                   17361: Process selected filters form course search form and pass to lonnet::courseiddump
                   17362: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17363: 
                   17364: Inputs:
                   17365: 
                   17366: dom - domain being searched 
                   17367: 
                   17368: type - course type ('Course' or 'Community' or '.' if any).
                   17369: 
                   17370: filter - anonymous hash of criteria and their values
                   17371: 
                   17372: numtitles - for institutional codes - number of categories
                   17373: 
                   17374: cloneruname - optional username of new course owner
                   17375: 
                   17376: clonerudom - optional domain of new course owner
                   17377: 
1.1221    raeburn  17378: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17379:             (used when DC is using course creation form)
                   17380: 
                   17381: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17382: 
1.1221    raeburn  17383: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17384:            (and so can clone automatically)
                   17385: 
                   17386: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17387: 
                   17388: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17389:               courses to clone 
1.1182    raeburn  17390: 
                   17391: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17392: 
                   17393: 
                   17394: Side Effects: None
                   17395: 
                   17396: =cut
                   17397: 
                   17398: 
                   17399: sub search_courses {
1.1221    raeburn  17400:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17401:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17402:     my (%courses,%showcourses,$cloner);
                   17403:     if (($filter->{'ownerfilter'} ne '') ||
                   17404:         ($filter->{'ownerdomfilter'} ne '')) {
                   17405:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17406:                                        $filter->{'ownerdomfilter'};
                   17407:     }
                   17408:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17409:         if (!$filter->{$item}) {
                   17410:             $filter->{$item}='.';
                   17411:         }
                   17412:     }
                   17413:     my $now = time;
                   17414:     my $timefilter =
                   17415:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17416:     my ($createdbefore,$createdafter);
                   17417:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17418:         $createdbefore = $now;
                   17419:         $createdafter = $now-$filter->{'createdfilter'};
                   17420:     }
                   17421:     my ($instcodefilter,$regexpok);
                   17422:     if ($numtitles) {
                   17423:         if ($env{'form.official'} eq 'on') {
                   17424:             $instcodefilter =
                   17425:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17426:             $regexpok = 1;
                   17427:         } elsif ($env{'form.official'} eq 'off') {
                   17428:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17429:             unless ($instcodefilter eq '') {
                   17430:                 $regexpok = -1;
                   17431:             }
                   17432:         }
                   17433:     } else {
                   17434:         $instcodefilter = $filter->{'instcodefilter'};
                   17435:     }
                   17436:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17437:     if ($type eq '') { $type = '.'; }
                   17438: 
                   17439:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17440:         $cloner = $cloneruname.':'.$clonerudom;
                   17441:     }
                   17442:     %courses = &Apache::lonnet::courseiddump($dom,
                   17443:                                              $filter->{'descriptfilter'},
                   17444:                                              $timefilter,
                   17445:                                              $instcodefilter,
                   17446:                                              $filter->{'combownerfilter'},
                   17447:                                              $filter->{'coursefilter'},
                   17448:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17449:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17450:                                              $filter->{'cloneableonly'},
                   17451:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17452:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17453:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17454:         my $ccrole;
                   17455:         if ($type eq 'Community') {
                   17456:             $ccrole = 'co';
                   17457:         } else {
                   17458:             $ccrole = 'cc';
                   17459:         }
                   17460:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17461:                                                      $filter->{'persondomfilter'},
                   17462:                                                      'userroles',undef,
                   17463:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17464:                                                      $dom);
                   17465:         foreach my $role (keys(%rolehash)) {
                   17466:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17467:             my $cid = $cdom.'_'.$cnum;
                   17468:             if (exists($courses{$cid})) {
                   17469:                 if (ref($courses{$cid}) eq 'HASH') {
                   17470:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17471:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17472:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17473:                         }
                   17474:                     } else {
                   17475:                         $courses{$cid}{roles} = [$courserole];
                   17476:                     }
                   17477:                     $showcourses{$cid} = $courses{$cid};
                   17478:                 }
                   17479:             }
                   17480:         }
                   17481:         %courses = %showcourses;
                   17482:     }
                   17483:     return %courses;
                   17484: }
                   17485: 
                   17486: =pod
                   17487: 
1.1181    raeburn  17488: =back
                   17489: 
1.1207    raeburn  17490: =head1 Routines for version requirements for current course.
                   17491: 
                   17492: =over 4
                   17493: 
                   17494: =item * &check_release_required()
                   17495: 
                   17496: Compares required LON-CAPA version with version on server, and
                   17497: if required version is newer looks for a server with the required version.
                   17498: 
                   17499: Looks first at servers in user's owen domain; if none suitable, looks at
                   17500: servers in course's domain are permitted to host sessions for user's domain.
                   17501: 
                   17502: Inputs:
                   17503: 
                   17504: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17505: 
                   17506: $courseid - Course ID of current course
                   17507: 
                   17508: $rolecode - User's current role in course (for switchserver query string).
                   17509: 
                   17510: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17511: 
                   17512: 
                   17513: Returns:
                   17514: 
                   17515: $switchserver - query string tp append to /adm/switchserver call (if 
                   17516:                 current server's LON-CAPA version is too old. 
                   17517: 
                   17518: $warning - Message is displayed if no suitable server could be found.
                   17519: 
                   17520: =cut
                   17521: 
                   17522: sub check_release_required {
                   17523:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17524:     my ($switchserver,$warning);
                   17525:     if ($required ne '') {
                   17526:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17527:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17528:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17529:             my $otherserver;
                   17530:             if (($major eq '' && $minor eq '') ||
                   17531:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17532:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17533:                 my $switchlcrev =
                   17534:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17535:                                                            $userdomserver);
                   17536:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17537:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17538:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17539:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17540:                     if ($cdom ne $env{'user.domain'}) {
                   17541:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17542:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17543:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17544:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17545:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17546:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17547:                         my $canhost =
                   17548:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17549:                                                               $coursedomserver,
                   17550:                                                               $remoterev,
                   17551:                                                               $udomdefaults{'remotesessions'},
                   17552:                                                               $defdomdefaults{'hostedsessions'});
                   17553: 
                   17554:                         if ($canhost) {
                   17555:                             $otherserver = $coursedomserver;
                   17556:                         } else {
                   17557:                             $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.");
                   17558:                         }
                   17559:                     } else {
                   17560:                         $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).");
                   17561:                     }
                   17562:                 } else {
                   17563:                     $otherserver = $userdomserver;
                   17564:                 }
                   17565:             }
                   17566:             if ($otherserver ne '') {
                   17567:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17568:             }
                   17569:         }
                   17570:     }
                   17571:     return ($switchserver,$warning);
                   17572: }
                   17573: 
                   17574: =pod
                   17575: 
                   17576: =item * &check_release_result()
                   17577: 
                   17578: Inputs:
                   17579: 
                   17580: $switchwarning - Warning message if no suitable server found to host session.
                   17581: 
                   17582: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17583:                 and current role.
                   17584: 
                   17585: Returns: HTML to display with information about requirement to switch server.
                   17586:          Either displaying warning with link to Roles/Courses screen or
                   17587:          display link to switchserver.
                   17588: 
1.1181    raeburn  17589: =cut
                   17590: 
1.1207    raeburn  17591: sub check_release_result {
                   17592:     my ($switchwarning,$switchserver) = @_;
                   17593:     my $output = &start_page('Selected course unavailable on this server').
                   17594:                  '<p class="LC_warning">';
                   17595:     if ($switchwarning) {
                   17596:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17597:         if (&show_course()) {
                   17598:             $output .= &mt('Display courses');
                   17599:         } else {
                   17600:             $output .= &mt('Display roles');
                   17601:         }
                   17602:         $output .= '</a>';
                   17603:     } elsif ($switchserver) {
                   17604:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17605:                    '<br />'.
                   17606:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17607:                    &mt('Switch Server').
                   17608:                    '</a>';
                   17609:     }
                   17610:     $output .= '</p>'.&end_page();
                   17611:     return $output;
                   17612: }
                   17613: 
                   17614: =pod
                   17615: 
                   17616: =item * &needs_coursereinit()
                   17617: 
                   17618: Determine if course contents stored for user's session needs to be
                   17619: refreshed, because content has changed since "Big Hash" last tied.
                   17620: 
                   17621: Check for change is made if time last checked is more than 10 minutes ago
                   17622: (by default).
                   17623: 
                   17624: Inputs:
                   17625: 
                   17626: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17627: 
                   17628: $interval (optional) - Time which may elapse (in s) between last check for content
                   17629:                        change in current course. (default: 600 s).  
                   17630: 
                   17631: Returns: an array; first element is:
                   17632: 
                   17633: =over 4
                   17634: 
                   17635: 'switch' - if content updates mean user's session
                   17636:            needs to be switched to a server running a newer LON-CAPA version
                   17637:  
                   17638: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17639:            on current server hosting user's session                
                   17640: 
                   17641: ''       - if no action required.
                   17642: 
                   17643: =back
                   17644: 
                   17645: If first item element is 'switch':
                   17646: 
                   17647: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17648: 
                   17649: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17650:                               and current role. 
                   17651: 
                   17652: otherwise: no other elements returned.
                   17653: 
                   17654: =back
                   17655: 
                   17656: =cut
                   17657: 
                   17658: sub needs_coursereinit {
                   17659:     my ($loncaparev,$interval) = @_;
                   17660:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17661:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17662:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17663:     my $now = time;
                   17664:     if ($interval eq '') {
                   17665:         $interval = 600;
                   17666:     }
                   17667:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17668:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17669:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17670:         if ($blocked) {
                   17671:             return ();
                   17672:         }
1.1207    raeburn  17673:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17674:         if ($lastchange > $env{'request.course.tied'}) {
                   17675:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17676:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17677:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17678:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17679:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17680:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17681:                     my ($switchserver,$switchwarning) =
                   17682:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17683:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17684:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17685:                         return ('switch',$switchwarning,$switchserver);
                   17686:                     }
                   17687:                 }
                   17688:             }
                   17689:             return ('update');
                   17690:         }
                   17691:     }
                   17692:     return ();
                   17693: }
1.1181    raeburn  17694: 
1.1083    raeburn  17695: sub update_content_constraints {
1.1326    raeburn  17696:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  17697:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17698:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  17699:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  17700:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17701:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17702:         if ($item eq 'resourcetag') {
                   17703:             if ($name eq 'responsetype') {
                   17704:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17705:             }
1.1307    raeburn  17706:         } elsif ($item eq 'course') {
                   17707:             if ($name eq 'courserestype') {
                   17708:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   17709:             }
1.1083    raeburn  17710:         }
                   17711:     }
                   17712:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17713:     if (defined($navmap)) {
1.1307    raeburn  17714:         my (%allresponses,%allcrsrestypes);
                   17715:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   17716:             if ($res->is_tool()) {
                   17717:                 if ($allcrsrestypes{'exttool'}) {
                   17718:                     $allcrsrestypes{'exttool'} ++;
                   17719:                 } else {
                   17720:                     $allcrsrestypes{'exttool'} = 1;
                   17721:                 }
                   17722:                 next;
                   17723:             }
1.1083    raeburn  17724:             my %responses = $res->responseTypes();
                   17725:             foreach my $key (keys(%responses)) {
                   17726:                 next unless(exists($checkresponsetypes{$key}));
                   17727:                 $allresponses{$key} += $responses{$key};
                   17728:             }
                   17729:         }
                   17730:         foreach my $key (keys(%allresponses)) {
                   17731:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17732:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17733:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17734:             }
                   17735:         }
1.1307    raeburn  17736:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  17737:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  17738:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17739:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17740:             }
                   17741:         }
1.1083    raeburn  17742:         undef($navmap);
                   17743:     }
1.1326    raeburn  17744:     my (@resources,@order,@resparms,@zombies);
                   17745:     if ($keeporder) {
                   17746:         use LONCAPA::map;
                   17747:         @resources = @LONCAPA::map::resources;
                   17748:         @order = @LONCAPA::map::order;
                   17749:         @resparms = @LONCAPA::map::resparms;
                   17750:         @zombies = @LONCAPA::map::zombies;
                   17751:     }
1.1308    raeburn  17752:     my $suppmap = 'supplemental.sequence';
                   17753:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   17754:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   17755:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  17756:     if ($keeporder) {
                   17757:         @LONCAPA::map::resources = @resources;
                   17758:         @LONCAPA::map::order = @order;
                   17759:         @LONCAPA::map::resparms = @resparms;
                   17760:         @LONCAPA::map::zombies = @zombies;
                   17761:     }
1.1308    raeburn  17762:     if ($supptools) {
                   17763:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   17764:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17765:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   17766:         }
                   17767:     }
1.1083    raeburn  17768:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17769:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17770:     }
                   17771:     return;
                   17772: }
                   17773: 
1.1110    raeburn  17774: sub allmaps_incourse {
                   17775:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17776:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17777:         $cid = $env{'request.course.id'};
                   17778:         $cdom = $env{'course.'.$cid.'.domain'};
                   17779:         $cnum = $env{'course.'.$cid.'.num'};
                   17780:         $chome = $env{'course.'.$cid.'.home'};
                   17781:     }
                   17782:     my %allmaps = ();
                   17783:     my $lastchange =
                   17784:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17785:     if ($lastchange > $env{'request.course.tied'}) {
                   17786:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17787:         unless ($ferr) {
1.1326    raeburn  17788:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  17789:         }
                   17790:     }
                   17791:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17792:     if (defined($navmap)) {
                   17793:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17794:             $allmaps{$res->src()} = 1;
                   17795:         }
                   17796:     }
                   17797:     return \%allmaps;
                   17798: }
                   17799: 
1.1083    raeburn  17800: sub parse_supplemental_title {
                   17801:     my ($title) = @_;
                   17802: 
                   17803:     my ($foldertitle,$renametitle);
                   17804:     if ($title =~ /&amp;&amp;&amp;/) {
                   17805:         $title = &HTML::Entites::decode($title);
                   17806:     }
                   17807:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17808:         $renametitle=$4;
                   17809:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17810:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17811:         my $name =  &plainname($uname,$udom);
                   17812:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17813:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17814:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17815:             $name.': <br />'.$foldertitle;
                   17816:     }
                   17817:     if (wantarray) {
                   17818:         return ($title,$foldertitle,$renametitle);
                   17819:     }
                   17820:     return $title;
                   17821: }
                   17822: 
1.1143    raeburn  17823: sub recurse_supplemental {
1.1308    raeburn  17824:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  17825:     if ($suppmap) {
                   17826:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17827:         if ($fatal) {
                   17828:             $errors ++;
                   17829:         } else {
                   17830:             if ($#LONCAPA::map::resources > 0) {
                   17831:                 foreach my $res (@LONCAPA::map::resources) {
                   17832:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17833:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17834:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  17835:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   17836:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  17837:                         } else {
1.1308    raeburn  17838:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   17839:                                 $numexttools ++;
                   17840:                             }
1.1143    raeburn  17841:                             $numfiles ++;
                   17842:                         }
                   17843:                     }
                   17844:                 }
                   17845:             }
                   17846:         }
                   17847:     }
1.1308    raeburn  17848:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  17849: }
                   17850: 
1.1101    raeburn  17851: sub symb_to_docspath {
1.1267    raeburn  17852:     my ($symb,$navmapref) = @_;
                   17853:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17854:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17855:     if ($resurl=~/\.(sequence|page)$/) {
                   17856:         $mapurl=$resurl;
                   17857:     } elsif ($resurl eq 'adm/navmaps') {
                   17858:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17859:     }
                   17860:     my $mapresobj;
1.1267    raeburn  17861:     unless (ref($$navmapref)) {
                   17862:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17863:     }
                   17864:     if (ref($$navmapref)) {
                   17865:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17866:     }
                   17867:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17868:     my $type=$2;
                   17869:     my $path;
                   17870:     if (ref($mapresobj)) {
                   17871:         my $pcslist = $mapresobj->map_hierarchy();
                   17872:         if ($pcslist ne '') {
                   17873:             foreach my $pc (split(/,/,$pcslist)) {
                   17874:                 next if ($pc <= 1);
1.1267    raeburn  17875:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17876:                 if (ref($res)) {
                   17877:                     my $thisurl = $res->src();
                   17878:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17879:                     my $thistitle = $res->title();
                   17880:                     $path .= '&'.
                   17881:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17882:                              &escape($thistitle).
1.1101    raeburn  17883:                              ':'.$res->randompick().
                   17884:                              ':'.$res->randomout().
                   17885:                              ':'.$res->encrypted().
                   17886:                              ':'.$res->randomorder().
                   17887:                              ':'.$res->is_page();
                   17888:                 }
                   17889:             }
                   17890:         }
                   17891:         $path =~ s/^\&//;
                   17892:         my $maptitle = $mapresobj->title();
                   17893:         if ($mapurl eq 'default') {
1.1129    raeburn  17894:             $maptitle = 'Main Content';
1.1101    raeburn  17895:         }
                   17896:         $path .= (($path ne '')? '&' : '').
                   17897:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17898:                  &escape($maptitle).
1.1101    raeburn  17899:                  ':'.$mapresobj->randompick().
                   17900:                  ':'.$mapresobj->randomout().
                   17901:                  ':'.$mapresobj->encrypted().
                   17902:                  ':'.$mapresobj->randomorder().
                   17903:                  ':'.$mapresobj->is_page();
                   17904:     } else {
                   17905:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17906:         my $ispage = (($type eq 'page')? 1 : '');
                   17907:         if ($mapurl eq 'default') {
1.1129    raeburn  17908:             $maptitle = 'Main Content';
1.1101    raeburn  17909:         }
                   17910:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17911:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17912:     }
                   17913:     unless ($mapurl eq 'default') {
                   17914:         $path = 'default&'.
1.1146    raeburn  17915:                 &escape('Main Content').
1.1101    raeburn  17916:                 ':::::&'.$path;
                   17917:     }
                   17918:     return $path;
                   17919: }
                   17920: 
1.1094    raeburn  17921: sub captcha_display {
1.1327    raeburn  17922:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17923:     my ($output,$error);
1.1234    raeburn  17924:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  17925:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17926:     if ($captcha eq 'original') {
1.1094    raeburn  17927:         $output = &create_captcha();
                   17928:         unless ($output) {
1.1172    raeburn  17929:             $error = 'captcha';
1.1094    raeburn  17930:         }
                   17931:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17932:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17933:         unless ($output) {
1.1172    raeburn  17934:             $error = 'recaptcha';
1.1094    raeburn  17935:         }
                   17936:     }
1.1234    raeburn  17937:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17938: }
                   17939: 
                   17940: sub captcha_response {
1.1327    raeburn  17941:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17942:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  17943:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17944:     if ($captcha eq 'original') {
1.1094    raeburn  17945:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17946:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17947:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17948:     } else {
                   17949:         $captcha_chk = 1;
                   17950:     }
                   17951:     return ($captcha_chk,$captcha_error);
                   17952: }
                   17953: 
                   17954: sub get_captcha_config {
1.1327    raeburn  17955:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  17956:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17957:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17958:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17959:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17960:     if ($context eq 'usercreation') {
                   17961:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17962:         if (ref($domconfig{$context}) eq 'HASH') {
                   17963:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17964:             if (ref($hashtocheck) eq 'HASH') {
                   17965:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17966:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17967:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17968:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17969:                     }
                   17970:                     if ($privkey && $pubkey) {
                   17971:                         $captcha = 'recaptcha';
1.1234    raeburn  17972:                         $version = $hashtocheck->{'recaptchaversion'};
                   17973:                         if ($version ne '2') {
                   17974:                             $version = 1;
                   17975:                         }
1.1095    raeburn  17976:                     } else {
                   17977:                         $captcha = 'original';
                   17978:                     }
                   17979:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17980:                     $captcha = 'original';
                   17981:                 }
1.1094    raeburn  17982:             }
1.1095    raeburn  17983:         } else {
                   17984:             $captcha = 'captcha';
                   17985:         }
                   17986:     } elsif ($context eq 'login') {
                   17987:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17988:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17989:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17990:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17991:             if ($privkey && $pubkey) {
                   17992:                 $captcha = 'recaptcha';
1.1234    raeburn  17993:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17994:                 if ($version ne '2') {
                   17995:                     $version = 1; 
                   17996:                 }
1.1095    raeburn  17997:             } else {
                   17998:                 $captcha = 'original';
1.1094    raeburn  17999:             }
1.1095    raeburn  18000:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18001:             $captcha = 'original';
1.1094    raeburn  18002:         }
1.1327    raeburn  18003:     } elsif ($context eq 'passwords') {
                   18004:         if ($dom_in_effect) {
                   18005:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18006:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18007:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18008:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18009:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18010:                 }
                   18011:                 if ($privkey && $pubkey) {
                   18012:                     $captcha = 'recaptcha';
                   18013:                     $version = $passwdconf{'recaptchaversion'};
                   18014:                     if ($version ne '2') {
                   18015:                         $version = 1;
                   18016:                     }
                   18017:                 } else {
                   18018:                     $captcha = 'original';
                   18019:                 }
                   18020:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18021:                 $captcha = 'original';
                   18022:             }
                   18023:         }
                   18024:     } 
1.1234    raeburn  18025:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18026: }
                   18027: 
                   18028: sub create_captcha {
                   18029:     my %captcha_params = &captcha_settings();
                   18030:     my ($output,$maxtries,$tries) = ('',10,0);
                   18031:     while ($tries < $maxtries) {
                   18032:         $tries ++;
                   18033:         my $captcha = Authen::Captcha->new (
                   18034:                                            output_folder => $captcha_params{'output_dir'},
                   18035:                                            data_folder   => $captcha_params{'db_dir'},
                   18036:                                           );
                   18037:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18038: 
                   18039:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18040:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   18041:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18042:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   18043:                       '<br />'.
                   18044:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18045:             last;
                   18046:         }
                   18047:     }
1.1323    raeburn  18048:     if ($output eq '') {
                   18049:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18050:     }
1.1094    raeburn  18051:     return $output;
                   18052: }
                   18053: 
                   18054: sub captcha_settings {
                   18055:     my %captcha_params = (
                   18056:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18057:                            www_output_dir => "/captchaspool",
                   18058:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18059:                            numchars       => '5',
                   18060:                          );
                   18061:     return %captcha_params;
                   18062: }
                   18063: 
                   18064: sub check_captcha {
                   18065:     my ($captcha_chk,$captcha_error);
                   18066:     my $code = $env{'form.code'};
                   18067:     my $md5sum = $env{'form.crypt'};
                   18068:     my %captcha_params = &captcha_settings();
                   18069:     my $captcha = Authen::Captcha->new(
                   18070:                       output_folder => $captcha_params{'output_dir'},
                   18071:                       data_folder   => $captcha_params{'db_dir'},
                   18072:                   );
1.1109    raeburn  18073:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18074:     my %captcha_hash = (
                   18075:                         0       => 'Code not checked (file error)',
                   18076:                        -1      => 'Failed: code expired',
                   18077:                        -2      => 'Failed: invalid code (not in database)',
                   18078:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18079:     );
                   18080:     if ($captcha_chk != 1) {
                   18081:         $captcha_error = $captcha_hash{$captcha_chk}
                   18082:     }
                   18083:     return ($captcha_chk,$captcha_error);
                   18084: }
                   18085: 
                   18086: sub create_recaptcha {
1.1234    raeburn  18087:     my ($pubkey,$version) = @_;
                   18088:     if ($version >= 2) {
                   18089:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   18090:     } else {
                   18091:         my $use_ssl;
                   18092:         if ($ENV{'SERVER_PORT'} == 443) {
                   18093:             $use_ssl = 1;
                   18094:         }
                   18095:         my $captcha = Captcha::reCAPTCHA->new;
                   18096:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18097:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18098:                &mt('If the text is hard to read, [_1] will replace them.',
                   18099:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18100:                '<br /><br />';
                   18101:     }
1.1094    raeburn  18102: }
                   18103: 
                   18104: sub check_recaptcha {
1.1234    raeburn  18105:     my ($privkey,$version) = @_;
1.1094    raeburn  18106:     my $captcha_chk;
1.1234    raeburn  18107:     if ($version >= 2) {
                   18108:         my %info = (
                   18109:                      secret   => $privkey, 
                   18110:                      response => $env{'form.g-recaptcha-response'},
                   18111:                      remoteip => $ENV{'REMOTE_ADDR'},
                   18112:                    );
1.1280    raeburn  18113:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18114:         $request->content(join('&',map {
                   18115:                          my $name = escape($_);
                   18116:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18117:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18118:                          : &escape($info{$_}) );
                   18119:         } keys(%info)));
                   18120:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18121:         if ($response->is_success)  {
                   18122:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18123:             if (ref($data) eq 'HASH') {
                   18124:                 if ($data->{'success'}) {
                   18125:                     $captcha_chk = 1;
                   18126:                 }
                   18127:             }
                   18128:         }
                   18129:     } else {
                   18130:         my $captcha = Captcha::reCAPTCHA->new;
                   18131:         my $captcha_result =
                   18132:             $captcha->check_answer(
                   18133:                                     $privkey,
                   18134:                                     $ENV{'REMOTE_ADDR'},
                   18135:                                     $env{'form.recaptcha_challenge_field'},
                   18136:                                     $env{'form.recaptcha_response_field'},
                   18137:                                   );
                   18138:         if ($captcha_result->{is_valid}) {
                   18139:             $captcha_chk = 1;
                   18140:         }
1.1094    raeburn  18141:     }
                   18142:     return $captcha_chk;
                   18143: }
                   18144: 
1.1174    raeburn  18145: sub emailusername_info {
1.1244    raeburn  18146:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18147:     my %titles = &Apache::lonlocal::texthash (
                   18148:                      lastname      => 'Last Name',
                   18149:                      firstname     => 'First Name',
                   18150:                      institution   => 'School/college/university',
                   18151:                      location      => "School's city, state/province, country",
                   18152:                      web           => "School's web address",
                   18153:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18154:                      id            => 'Student/Employee ID',
1.1174    raeburn  18155:                  );
                   18156:     return (\@fields,\%titles);
                   18157: }
                   18158: 
1.1161    raeburn  18159: sub cleanup_html {
                   18160:     my ($incoming) = @_;
                   18161:     my $outgoing;
                   18162:     if ($incoming ne '') {
                   18163:         $outgoing = $incoming;
                   18164:         $outgoing =~ s/;/&#059;/g;
                   18165:         $outgoing =~ s/\#/&#035;/g;
                   18166:         $outgoing =~ s/\&/&#038;/g;
                   18167:         $outgoing =~ s/</&#060;/g;
                   18168:         $outgoing =~ s/>/&#062;/g;
                   18169:         $outgoing =~ s/\(/&#040/g;
                   18170:         $outgoing =~ s/\)/&#041;/g;
                   18171:         $outgoing =~ s/"/&#034;/g;
                   18172:         $outgoing =~ s/'/&#039;/g;
                   18173:         $outgoing =~ s/\$/&#036;/g;
                   18174:         $outgoing =~ s{/}{&#047;}g;
                   18175:         $outgoing =~ s/=/&#061;/g;
                   18176:         $outgoing =~ s/\\/&#092;/g
                   18177:     }
                   18178:     return $outgoing;
                   18179: }
                   18180: 
1.1190    musolffc 18181: # Checks for critical messages and returns a redirect url if one exists.
                   18182: # $interval indicates how often to check for messages.
1.1282    raeburn  18183: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18184: sub critical_redirect {
1.1282    raeburn  18185:     my ($interval,$context) = @_;
1.1190    musolffc 18186:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18187:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18188:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18189:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18190:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   18191:             if ($blocked) {
                   18192:                 my $checkrole = "cm./$cdom/$cnum";
                   18193:                 if ($env{'request.course.sec'} ne '') {
                   18194:                     $checkrole .= "/$env{'request.course.sec'}";
                   18195:                 }
                   18196:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18197:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18198:                     return;
                   18199:                 }
                   18200:             }
                   18201:         }
1.1190    musolffc 18202:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18203:                                         $env{'user.name'});
                   18204:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18205:         my $redirecturl;
1.1190    musolffc 18206:         if ($what[0]) {
                   18207: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   18208: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18209: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18210:                 return (1, $url);
1.1190    musolffc 18211:             }
1.1191    raeburn  18212:         }
                   18213:     } 
                   18214:     return ();
1.1190    musolffc 18215: }
                   18216: 
1.1174    raeburn  18217: # Use:
                   18218: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18219: #
                   18220: ##################################################
                   18221: #          password associated functions         #
                   18222: ##################################################
                   18223: sub des_keys {
                   18224:     # Make a new key for DES encryption.
                   18225:     # Each key has two parts which are returned separately.
                   18226:     # Please note:  Each key must be passed through the &hex function
                   18227:     # before it is output to the web browser.  The hex versions cannot
                   18228:     # be used to decrypt.
                   18229:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18230:                 '8','9','a','b','c','d','e','f');
                   18231:     my $lkey='';
                   18232:     for (0..7) {
                   18233:         $lkey.=$hexstr[rand(15)];
                   18234:     }
                   18235:     my $ukey='';
                   18236:     for (0..7) {
                   18237:         $ukey.=$hexstr[rand(15)];
                   18238:     }
                   18239:     return ($lkey,$ukey);
                   18240: }
                   18241: 
                   18242: sub des_decrypt {
                   18243:     my ($key,$cyphertext) = @_;
                   18244:     my $keybin=pack("H16",$key);
                   18245:     my $cypher;
                   18246:     if ($Crypt::DES::VERSION>=2.03) {
                   18247:         $cypher=new Crypt::DES $keybin;
                   18248:     } else {
                   18249:         $cypher=new DES $keybin;
                   18250:     }
1.1233    raeburn  18251:     my $plaintext='';
                   18252:     my $cypherlength = length($cyphertext);
                   18253:     my $numchunks = int($cypherlength/32);
                   18254:     for (my $j=0; $j<$numchunks; $j++) {
                   18255:         my $start = $j*32;
                   18256:         my $cypherblock = substr($cyphertext,$start,32);
                   18257:         my $chunk =
                   18258:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18259:         $chunk .=
                   18260:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18261:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18262:         $plaintext .= $chunk;
                   18263:     }
1.1174    raeburn  18264:     return $plaintext;
                   18265: }
                   18266: 
1.1344    raeburn  18267: sub get_requested_shorturls {
1.1309    raeburn  18268:     my ($cdom,$cnum,$navmap) = @_;
                   18269:     return unless (ref($navmap));
1.1344    raeburn  18270:     my ($numnew,$errors);
1.1309    raeburn  18271:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18272:     if (@toshorten) {
                   18273:         my (%maps,%resources,%titles);
                   18274:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18275:                                                                'shorturls',$cdom,$cnum);
                   18276:         if (keys(%resources)) {
1.1344    raeburn  18277:             my %tocreate;
1.1309    raeburn  18278:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18279:                 my $symb = $resources{$item};
                   18280:                 if ($symb) {
                   18281:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18282:                 }
                   18283:             }
1.1344    raeburn  18284:             if (keys(%tocreate)) {
                   18285:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18286:                                                       \%tocreate);
                   18287:             }
1.1309    raeburn  18288:         }
1.1344    raeburn  18289:     }
                   18290:     return ($numnew,$errors);
                   18291: }
                   18292: 
                   18293: sub make_short_symbs {
                   18294:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18295:     my ($numnew,@errors);
                   18296:     if (ref($tocreateref) eq 'HASH') {
                   18297:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18298:         if (keys(%tocreate)) {
                   18299:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18300:             my $su = Short::URL->new(no_vowels => 1);
                   18301:             my $init = '';
                   18302:             my (%newunique,%addcourse,%courseonly,%failed);
                   18303:             # get lock on tiny db
                   18304:             my $now = time;
1.1344    raeburn  18305:             if ($lockuser eq '') {
                   18306:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18307:             }
1.1309    raeburn  18308:             my $lockhash = {
1.1344    raeburn  18309:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18310:                             };
                   18311:             my $tries = 0;
                   18312:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18313:             my ($code,$error);
                   18314:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18315:                 $tries ++;
                   18316:                 sleep 1;
1.1319    raeburn  18317:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18318:             }
                   18319:             if ($gotlock eq 'ok') {
                   18320:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18321:                                        \%addcourse,\%courseonly,\%failed);
                   18322:                 if (keys(%failed)) {
                   18323:                     my $numfailed = scalar(keys(%failed));
                   18324:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18325:                 }
                   18326:                 if (keys(%newunique)) {
                   18327:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18328:                     if ($putres eq 'ok') {
                   18329:                         $numnew = scalar(keys(%newunique));
                   18330:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18331:                         unless ($newputres eq 'ok') {
                   18332:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18333:                         }
                   18334:                     } else {
                   18335:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18336:                     }
                   18337:                 }
                   18338:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18339:                 unless ($dellockres eq 'ok') {
                   18340:                     push(@errors,&mt('error: could not release lockfile'));
                   18341:                 }
                   18342:             } else {
                   18343:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18344:             }
                   18345:             if (keys(%courseonly)) {
                   18346:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18347:                 if ($result ne 'ok') {
                   18348:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18349:                 }
                   18350:             }
                   18351:         }
                   18352:     }
                   18353:     return ($numnew,\@errors);
                   18354: }
                   18355: 
                   18356: sub shorten_symbs {
                   18357:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18358:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18359:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18360:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18361:     my (%possibles,%collisions);
                   18362:     foreach my $key (keys(%{$tocreate})) {
                   18363:         my $num = String::CRC32::crc32($key);
                   18364:         my $tiny = $su->encode($num,$init);
                   18365:         if ($tiny) {
                   18366:             $possibles{$tiny} = $key;
                   18367:         }
                   18368:     }
                   18369:     if (!$init) {
                   18370:         $init = 1;
                   18371:     } else {
                   18372:         $init ++;
                   18373:     }
                   18374:     if (keys(%possibles)) {
                   18375:         my @posstiny = keys(%possibles);
                   18376:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18377:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18378:         if (keys(%currtiny)) {
                   18379:             foreach my $key (keys(%currtiny)) {
                   18380:                 next if ($currtiny{$key} eq '');
                   18381:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18382:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18383:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18384:                         $courseonly->{$tsymb} = $key;
                   18385:                     }
                   18386:                 } else {
                   18387:                     $collisions{$possibles{$key}} = 1;
                   18388:                 }
                   18389:                 delete($possibles{$key});
                   18390:             }
                   18391:         }
                   18392:         foreach my $key (keys(%possibles)) {
                   18393:             $newunique->{$key} = $possibles{$key};
                   18394:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18395:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18396:                 $addcourse->{$tsymb} = $key;
                   18397:             }
                   18398:         }
                   18399:     }
                   18400:     if (keys(%collisions)) {
                   18401:         if ($init <5) {
                   18402:             if (!$init) {
                   18403:                 $init = 1;
                   18404:             } else {
                   18405:                 $init ++;
                   18406:             }
                   18407:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18408:                                    $newunique,$addcourse,$courseonly,$failed);
                   18409:         } else {
                   18410:             foreach my $key (keys(%collisions)) {
                   18411:                 $failed->{$key} = 1;
                   18412:             }
                   18413:         }
                   18414:     }
                   18415:     return $init;
                   18416: }
                   18417: 
1.1328    raeburn  18418: sub is_nonframeable {
1.1329    raeburn  18419:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18420:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18421:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18422: 
                   18423:     $remprotocol = lc($remprotocol);
                   18424:     $remhost = lc($remhost);
                   18425:     my $remport = 80;
                   18426:     if ($remprotocol eq 'https') {
                   18427:         $remport = 443;
                   18428:     }
1.1330    raeburn  18429:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18430:     if ($cached) {
                   18431:         unless ($nocache) {
                   18432:             if ($result) {
                   18433:                 return 1;
                   18434:             } else {
                   18435:                 return 0;
                   18436:             }
                   18437:         }
                   18438:     }
1.1328    raeburn  18439:     my $uselink;
                   18440:     my $request = new HTTP::Request('HEAD',$url);
                   18441:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18442:     if ($response->is_success()) {
                   18443:         my $secpolicy = lc($response->header('content-security-policy'));
                   18444:         my $xframeop = lc($response->header('x-frame-options'));
                   18445:         $secpolicy =~ s/^\s+|\s+$//g;
                   18446:         $xframeop =~ s/^\s+|\s+$//g;
                   18447:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18448:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18449:             my ($origin,$protocol,$port);
                   18450:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18451:                 $port = $ENV{'SERVER_PORT'};
                   18452:             } else {
                   18453:                 $port = 80;
                   18454:             }
                   18455:             if ($absolute eq '') {
                   18456:                 $protocol = 'http:';
                   18457:                 if ($port == 443) {
                   18458:                     $protocol = 'https:';
                   18459:                 }
                   18460:                 $origin = $protocol.'//'.lc($hostname);
                   18461:             } else {
                   18462:                 $origin = lc($absolute);
                   18463:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18464:             }
                   18465:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18466:                 my $framepolicy = $1;
                   18467:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18468:                 my @policies = split(/\s+/,$framepolicy);
                   18469:                 if (@policies) {
                   18470:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18471:                         $uselink = 1;
                   18472:                     } else {
                   18473:                         $uselink = 1;
                   18474:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18475:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18476:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18477:                             undef($uselink);
                   18478:                         }
                   18479:                         if ($uselink) {
                   18480:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18481:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18482:                                     undef($uselink);
                   18483:                                 }
                   18484:                             }
                   18485:                         }
                   18486:                         if ($uselink) {
                   18487:                             my @possok;
                   18488:                             if ($ip ne '') {
                   18489:                                 push(@possok,$ip);
                   18490:                             }
                   18491:                             my $hoststr = '';
                   18492:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18493:                                 if ($hoststr eq '') {
                   18494:                                     $hoststr = $part;
                   18495:                                 } else {
                   18496:                                     $hoststr = "$part.$hoststr";
                   18497:                                 }
                   18498:                                 if ($hoststr eq $hostname) {
                   18499:                                     push(@possok,$hostname);
                   18500:                                 } else {
                   18501:                                     push(@possok,"*.$hoststr");
                   18502:                                 }
                   18503:                             }
                   18504:                             if (@possok) {
                   18505:                                 foreach my $poss (@possok) {
                   18506:                                     last if (!$uselink);
                   18507:                                     foreach my $policy (@policies) {
                   18508:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18509:                                             undef($uselink);
                   18510:                                             last;
                   18511:                                         }
                   18512:                                     }
                   18513:                                 }
                   18514:                             }
                   18515:                         }
                   18516:                     }
                   18517:                 }
                   18518:             } elsif ($xframeop ne '') {
                   18519:                 $uselink = 1;
                   18520:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18521:                 if (@policies) {
                   18522:                     unless (grep(/^deny$/,@policies)) {
                   18523:                         if ($origin ne '') {
                   18524:                             if (grep(/^sameorigin$/,@policies)) {
                   18525:                                 if ($remotehost eq $origin) {
                   18526:                                     undef($uselink);
                   18527:                                 }
                   18528:                             }
                   18529:                             if ($uselink) {
                   18530:                                 foreach my $policy (@policies) {
                   18531:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18532:                                         my $allowfrom = $1;
                   18533:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18534:                                             undef($uselink);
                   18535:                                             last;
                   18536:                                         }
                   18537:                                     }
                   18538:                                 }
                   18539:                             }
                   18540:                         }
                   18541:                     }
                   18542:                 }
                   18543:             }
                   18544:         }
                   18545:     }
1.1329    raeburn  18546:     if ($nocache) {
                   18547:         if ($cached) {
                   18548:             my $devalidate;
                   18549:             if ($uselink && !$result) {
                   18550:                 $devalidate = 1;
                   18551:             } elsif (!$uselink && $result) {
                   18552:                 $devalidate = 1;
                   18553:             }
                   18554:             if ($devalidate) {
                   18555:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18556:             }
                   18557:         }
                   18558:     } else {
                   18559:         if ($uselink) {
                   18560:             $result = 1;
                   18561:         } else {
                   18562:             $result = 0;
                   18563:         }
                   18564:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18565:     }
1.1328    raeburn  18566:     return $uselink;
                   18567: }
                   18568: 
1.112     bowersj2 18569: 1;
                   18570: __END__;
1.41      ng       18571: 

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