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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1377  ! raeburn     4: # $Id: loncommon.pm,v 1.1376 2022/02/14 01:15:24 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.1309    raeburn    89: use String::CRC32();
                     90: use Short::URL();
1.117     www        91: 
1.517     raeburn    92: # ---------------------------------------------- Designs
                     93: use vars qw(%defaultdesign);
                     94: 
1.22      www        95: my $readit;
                     96: 
1.517     raeburn    97: 
1.157     matthew    98: ##
                     99: ## Global Variables
                    100: ##
1.46      matthew   101: 
1.643     foxr      102: 
                    103: # ----------------------------------------------- SSI with retries:
                    104: #
                    105: 
                    106: =pod
                    107: 
1.648     raeburn   108: =head1 Server Side include with retries:
1.643     foxr      109: 
                    110: =over 4
                    111: 
1.648     raeburn   112: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      113: 
                    114: Performs an ssi with some number of retries.  Retries continue either
                    115: until the result is ok or until the retry count supplied by the
                    116: caller is exhausted.  
                    117: 
                    118: Inputs:
1.648     raeburn   119: 
                    120: =over 4
                    121: 
1.643     foxr      122: resource   - Identifies the resource to insert.
1.648     raeburn   123: 
1.643     foxr      124: retries    - Count of the number of retries allowed.
1.648     raeburn   125: 
1.643     foxr      126: form       - Hash that identifies the rendering options.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: Returns:
                    131: 
                    132: =over 4
                    133: 
1.643     foxr      134: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   135: 
1.643     foxr      136: response   - The response from the last attempt (which may or may not have been successful.
                    137: 
1.648     raeburn   138: =back
                    139: 
                    140: =back
                    141: 
1.643     foxr      142: =cut
                    143: 
                    144: sub ssi_with_retries {
                    145:     my ($resource, $retries, %form) = @_;
                    146: 
                    147: 
                    148:     my $ok = 0;			# True if we got a good response.
                    149:     my $content;
                    150:     my $response;
                    151: 
                    152:     # Try to get the ssi done. within the retries count:
                    153: 
                    154:     do {
                    155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    156: 	$ok      = $response->is_success;
1.650     www       157:         if (!$ok) {
                    158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    159:         }
1.643     foxr      160: 	$retries--;
                    161:     } while (!$ok && ($retries > 0));
                    162: 
                    163:     if (!$ok) {
                    164: 	$content = '';		# On error return an empty content.
                    165:     }
                    166:     return ($content, $response);
                    167: 
                    168: }
                    169: 
                    170: 
                    171: 
1.20      www       172: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  173: my %language;
1.124     www       174: my %supported_language;
1.1088    foxr      175: my %supported_codes;
1.1048    foxr      176: my %latex_language;		# For choosing hyphenation in <transl..>
                    177: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  178: my %cprtag;
1.192     taceyjo1  179: my %scprtag;
1.351     www       180: my %fe; my %fd; my %fm;
1.41      ng        181: my %category_extensions;
1.12      harris41  182: 
1.46      matthew   183: # ---------------------------------------------- Thesaurus variables
1.144     matthew   184: #
                    185: # %Keywords:
                    186: #      A hash used by &keyword to determine if a word is considered a keyword.
                    187: # $thesaurus_db_file 
                    188: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   189: 
                    190: my %Keywords;
                    191: my $thesaurus_db_file;
                    192: 
1.144     matthew   193: #
                    194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    195: # thesaurus.tab, and filecategories.tab.
                    196: #
1.18      www       197: BEGIN {
1.46      matthew   198:     # Variable initialization
                    199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    200:     #
1.22      www       201:     unless ($readit) {
1.12      harris41  202: # ------------------------------------------------------------------- languages
                    203:     {
1.158     raeburn   204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    205:                                    '/language.tab';
1.1317    raeburn   206:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  207:             while (my $line = <$fh>) {
                    208:                 next if ($line=~/^\#/);
                    209:                 chomp($line);
1.1088    foxr      210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   211:                 $language{$key}=$val.' - '.$enc;
                    212:                 if ($sup) {
                    213:                     $supported_language{$key}=$sup;
1.1088    foxr      214: 		    $supported_codes{$key}   = $code;
1.158     raeburn   215:                 }
1.1048    foxr      216: 		if ($latex) {
                    217: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      218: 		    $latex_language{$code} = $latex;
1.1048    foxr      219: 		}
1.158     raeburn   220:             }
                    221:             close($fh);
                    222:         }
1.12      harris41  223:     }
                    224: # ------------------------------------------------------------------ copyrights
                    225:     {
1.158     raeburn   226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    227:                                   '/copyright.tab';
1.1317    raeburn   228:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  229:             while (my $line = <$fh>) {
                    230:                 next if ($line=~/^\#/);
                    231:                 chomp($line);
                    232:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   233:                 $cprtag{$key}=$val;
                    234:             }
                    235:             close($fh);
                    236:         }
1.12      harris41  237:     }
1.351     www       238: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  239:     {
                    240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    241:                                   '/source_copyright.tab';
1.1317    raeburn   242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  243:             while (my $line = <$fh>) {
                    244:                 next if ($line =~ /^\#/);
                    245:                 chomp($line);
                    246:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  247:                 $scprtag{$key}=$val;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251:     }
1.63      www       252: 
1.517     raeburn   253: # -------------------------------------------------------------- default domain designs
1.63      www       254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   255:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   256:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   257:         while (my $line = <$fh>) {
                    258:             next if ($line =~ /^\#/);
                    259:             chomp($line);
                    260:             my ($key,$val)=(split(/\=/,$line));
                    261:             if ($val) { $defaultdesign{$key}=$val; }
                    262:         }
                    263:         close($fh);
1.63      www       264:     }
                    265: 
1.15      harris41  266: # ------------------------------------------------------------- file categories
                    267:     {
1.158     raeburn   268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                                   '/filecategories.tab';
1.1317    raeburn   270:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  271: 	    while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   275:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   276:             }
                    277:             close($fh);
                    278:         }
                    279: 
1.15      harris41  280:     }
1.12      harris41  281: # ------------------------------------------------------------------ file types
                    282:     {
1.158     raeburn   283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    284:                '/filetypes.tab';
1.1317    raeburn   285:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  286:             while (my $line = <$fh>) {
                    287: 		next if ($line =~ /^\#/);
                    288: 		chomp($line);
                    289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   290:                 if ($descr ne '') {
                    291:                     $fe{$ending}=lc($emb);
                    292:                     $fd{$ending}=$descr;
1.351     www       293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   294:                 }
                    295:             }
                    296:             close($fh);
                    297:         }
1.12      harris41  298:     }
1.22      www       299:     &Apache::lonnet::logthis(
1.705     tempelho  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       301:     $readit=1;
1.46      matthew   302:     }  # end of unless($readit) 
1.32      matthew   303:     
                    304: }
1.112     bowersj2  305: 
1.42      matthew   306: ###############################################################
                    307: ##           HTML and Javascript Helper Functions            ##
                    308: ###############################################################
                    309: 
                    310: =pod 
                    311: 
1.112     bowersj2  312: =head1 HTML and Javascript Functions
1.42      matthew   313: 
1.112     bowersj2  314: =over 4
                    315: 
1.648     raeburn   316: =item * &browser_and_searcher_javascript()
1.112     bowersj2  317: 
                    318: X<browsing, javascript>X<searching, javascript>Returns a string
                    319: containing javascript with two functions, C<openbrowser> and
                    320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    321: tags.
1.42      matthew   322: 
1.648     raeburn   323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   324: 
                    325: inputs: formname, elementname, only, omit
                    326: 
                    327: formname and elementname indicate the name of the html form and name of
                    328: the element that the results of the browsing selection are to be placed in. 
                    329: 
                    330: Specifying 'only' will restrict the browser to displaying only files
1.185     www       331: with the given extension.  Can be a comma separated list.
1.42      matthew   332: 
                    333: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       334: with the given extension.  Can be a comma separated list.
1.42      matthew   335: 
1.648     raeburn   336: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   337: 
                    338: Inputs: formname, elementname
                    339: 
                    340: formname and elementname specify the name of the html form and the name
                    341: of the element the selection from the search results will be placed in.
1.542     raeburn   342: 
1.42      matthew   343: =cut
                    344: 
                    345: sub browser_and_searcher_javascript {
1.199     albertel  346:     my ($mode)=@_;
                    347:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  348:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   349:     return <<END;
1.219     albertel  350: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   351:     var editbrowser = null;
1.135     albertel  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       353:         var url = '$resurl/?';
1.42      matthew   354:         if (editbrowser == null) {
                    355:             url += 'launch=1&';
                    356:         }
                    357:         url += 'catalogmode=interactive&';
1.199     albertel  358:         url += 'mode=$mode&';
1.611     albertel  359:         url += 'inhibitmenu=yes&';
1.42      matthew   360:         url += 'form=' + formname + '&';
                    361:         if (only != null) {
                    362:             url += 'only=' + only + '&';
1.217     albertel  363:         } else {
                    364:             url += 'only=&';
                    365: 	}
1.42      matthew   366:         if (omit != null) {
                    367:             url += 'omit=' + omit + '&';
1.217     albertel  368:         } else {
                    369:             url += 'omit=&';
                    370: 	}
1.135     albertel  371:         if (titleelement != null) {
                    372:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  373:         } else {
                    374: 	    url += 'titleelement=&';
                    375: 	}
1.42      matthew   376:         url += 'element=' + elementname + '';
                    377:         var title = 'Browser';
1.435     albertel  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   379:         options += ',width=700,height=600';
                    380:         editbrowser = open(url,title,options,'1');
                    381:         editbrowser.focus();
                    382:     }
                    383:     var editsearcher;
1.135     albertel  384:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   385:         var url = '/adm/searchcat?';
                    386:         if (editsearcher == null) {
                    387:             url += 'launch=1&';
                    388:         }
                    389:         url += 'catalogmode=interactive&';
1.199     albertel  390:         url += 'mode=$mode&';
1.42      matthew   391:         url += 'form=' + formname + '&';
1.135     albertel  392:         if (titleelement != null) {
                    393:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  394:         } else {
                    395: 	    url += 'titleelement=&';
                    396: 	}
1.42      matthew   397:         url += 'element=' + elementname + '';
                    398:         var title = 'Search';
1.435     albertel  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   400:         options += ',width=700,height=600';
                    401:         editsearcher = open(url,title,options,'1');
                    402:         editsearcher.focus();
                    403:     }
1.219     albertel  404: // END LON-CAPA Internal -->
1.42      matthew   405: END
1.170     www       406: }
                    407: 
                    408: sub lastresurl {
1.258     albertel  409:     if ($env{'environment.lastresurl'}) {
                    410: 	return $env{'environment.lastresurl'}
1.170     www       411:     } else {
                    412: 	return '/res';
                    413:     }
                    414: }
                    415: 
                    416: sub storeresurl {
                    417:     my $resurl=&Apache::lonnet::clutter(shift);
                    418:     unless ($resurl=~/^\/res/) { return 0; }
                    419:     $resurl=~s/\/$//;
                    420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       422:     return 1;
1.42      matthew   423: }
                    424: 
1.74      www       425: sub studentbrowser_javascript {
1.111     www       426:    unless (
1.258     albertel  427:             (($env{'request.course.id'}) && 
1.302     albertel  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    430: 					  '/'.$env{'request.course.sec'})
                    431: 	      ))
1.258     albertel  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       433:           ) { return ''; }  
1.74      www       434:    return (<<'ENDSTDBRW');
1.776     bisitz    435: <script type="text/javascript" language="Javascript">
1.824     bisitz    436: // <![CDATA[
1.74      www       437:     var stdeditbrowser;
1.1337    raeburn   438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       439:         var url = '/adm/pickstudent?';
                    440:         var filter;
1.558     albertel  441: 	if (!ignorefilter) {
                    442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    443: 	}
1.74      www       444:         if (filter != null) {
                    445:            if (filter != '') {
                    446:                url += 'filter='+filter+'&';
                    447: 	   }
                    448:         }
                    449:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       450:                                     '&udomelement='+udom+
                    451:                                     '&clicker='+clicker;
1.111     www       452: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   453:         if (courseadv == 'condition') {
                    454:             if (document.getElementById('courseadv')) {
                    455:                 courseadv = document.getElementById('courseadv').value;
                    456:             }
                    457:         }
                    458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       459:         var title = 'Student_Browser';
1.74      www       460:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    461:         options += ',width=700,height=600';
                    462:         stdeditbrowser = open(url,title,options,'1');
                    463:         stdeditbrowser.focus();
                    464:     }
1.824     bisitz    465: // ]]>
1.74      www       466: </script>
                    467: ENDSTDBRW
                    468: }
1.42      matthew   469: 
1.1003    www       470: sub resourcebrowser_javascript {
                    471:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       472:    return (<<'ENDRESBRW');
1.1003    www       473: <script type="text/javascript" language="Javascript">
                    474: // <![CDATA[
                    475:     var reseditbrowser;
1.1004    www       476:     function openresbrowser(formname,reslink) {
1.1005    www       477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       478:         var title = 'Resource_Browser';
                    479:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       480:         options += ',width=700,height=500';
1.1004    www       481:         reseditbrowser = open(url,title,options,'1');
                    482:         reseditbrowser.focus();
1.1003    www       483:     }
                    484: // ]]>
                    485: </script>
1.1004    www       486: ENDRESBRW
1.1003    www       487: }
                    488: 
1.74      www       489: sub selectstudent_link {
1.1337    raeburn   490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  494:    if ($env{'request.course.id'}) {  
1.302     albertel  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    497: 					'/'.$env{'request.course.sec'})) {
1.111     www       498: 	   return '';
                    499:        }
1.999     www       500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   501:        if ($courseadv eq 'only') {
                    502:            $callargs .= ",'',1,'$courseadv'";
                    503:        } elsif ($courseadv eq 'none') {
                    504:            $callargs .= ",'','','$courseadv'";
                    505:        } elsif ($courseadv eq 'condition') {
                    506:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   507:        }
                    508:        return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    510:               &mt('Select User').'</a></span>';
1.74      www       511:    }
1.258     albertel  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       513:        $callargs .= ",'',1"; 
1.793     raeburn   514:        return '<span class="LC_nobreak">'.
                    515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    516:               &mt('Select User').'</a></span>';
1.111     www       517:    }
                    518:    return '';
1.91      www       519: }
                    520: 
1.1004    www       521: sub selectresource_link {
                    522:    my ($form,$reslink,$arg)=@_;
                    523:    
                    524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    526:    unless ($env{'request.course.id'}) { return $arg; }
                    527:    return '<span class="LC_nobreak">'.
                    528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    529:               $arg.'</a></span>';
                    530: }
                    531: 
                    532: 
                    533: 
1.653     raeburn   534: sub authorbrowser_javascript {
                    535:     return <<"ENDAUTHORBRW";
1.776     bisitz    536: <script type="text/javascript" language="JavaScript">
1.824     bisitz    537: // <![CDATA[
1.653     raeburn   538: var stdeditbrowser;
                    539: 
                    540: function openauthorbrowser(formname,udom) {
                    541:     var url = '/adm/pickauthor?';
                    542:     url += 'form='+formname+'&roledom='+udom;
                    543:     var title = 'Author_Browser';
                    544:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    545:     options += ',width=700,height=600';
                    546:     stdeditbrowser = open(url,title,options,'1');
                    547:     stdeditbrowser.focus();
                    548: }
                    549: 
1.824     bisitz    550: // ]]>
1.653     raeburn   551: </script>
                    552: ENDAUTHORBRW
                    553: }
                    554: 
1.91      www       555: sub coursebrowser_javascript {
1.1116    raeburn   556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   557:         $credits_element,$instcode) = @_;
1.932     raeburn   558:     my $wintitle = 'Course_Browser';
1.931     raeburn   559:     if ($crstype eq 'Community') {
1.932     raeburn   560:         $wintitle = 'Community_Browser';
1.909     raeburn   561:     }
1.876     raeburn   562:     my $id_functions = &javascript_index_functions();
                    563:     my $output = '
1.776     bisitz    564: <script type="text/javascript" language="JavaScript">
1.824     bisitz    565: // <![CDATA[
1.468     raeburn   566:     var stdeditbrowser;'."\n";
1.876     raeburn   567: 
                    568:     $output .= <<"ENDSTDBRW";
1.909     raeburn   569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       570:         var url = '/adm/pickcourse?';
1.895     raeburn   571:         var formid = getFormIdByName(formname);
1.876     raeburn   572:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  573:         if (domainfilter != null) {
                    574:            if (domainfilter != '') {
                    575:                url += 'domainfilter='+domainfilter+'&';
                    576: 	   }
                    577:         }
1.91      www       578:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  579: 	                            '&cdomelement='+udom+
                    580:                                     '&cnameelement='+desc;
1.468     raeburn   581:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   582:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   583:                 url += '&roleelement='+extra_element;
                    584:                 if (domainfilter == null || domainfilter == '') {
                    585:                     url += '&domainfilter='+extra_element;
                    586:                 }
1.234     raeburn   587:             }
1.468     raeburn   588:             else {
                    589:                 if (formname == 'portform') {
                    590:                     url += '&setroles='+extra_element;
1.800     raeburn   591:                 } else {
                    592:                     if (formname == 'rules') {
                    593:                         url += '&fixeddom='+extra_element; 
                    594:                     }
1.468     raeburn   595:                 }
                    596:             }     
1.230     raeburn   597:         }
1.909     raeburn   598:         if (type != null && type != '') {
                    599:             url += '&type='+type;
                    600:         }
                    601:         if (type_elem != null && type_elem != '') {
                    602:             url += '&typeelement='+type_elem;
                    603:         }
1.872     raeburn   604:         if (formname == 'ccrs') {
                    605:             var ownername = document.forms[formid].ccuname.value;
                    606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   607:             url += '&cloner='+ownername+':'+ownerdom;
                    608:             if (type == 'Course') {
                    609:                 url += '&crscode='+document.forms[formid].crscode.value;
                    610:             }
1.1221    raeburn   611:         }
                    612:         if (formname == 'requestcrs') {
                    613:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   614:         }
1.293     raeburn   615:         if (multflag !=null && multflag != '') {
                    616:             url += '&multiple='+multflag;
                    617:         }
1.909     raeburn   618:         var title = '$wintitle';
1.91      www       619:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    620:         options += ',width=700,height=600';
                    621:         stdeditbrowser = open(url,title,options,'1');
                    622:         stdeditbrowser.focus();
                    623:     }
1.876     raeburn   624: $id_functions
                    625: ENDSTDBRW
1.1116    raeburn   626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    628:                                       $credits_element);
1.876     raeburn   629:     }
                    630:     $output .= '
                    631: // ]]>
                    632: </script>';
                    633:     return $output;
                    634: }
                    635: 
                    636: sub javascript_index_functions {
                    637:     return <<"ENDJS";
                    638: 
                    639: function getFormIdByName(formname) {
                    640:     for (var i=0;i<document.forms.length;i++) {
                    641:         if (document.forms[i].name == formname) {
                    642:             return i;
                    643:         }
                    644:     }
                    645:     return -1;
                    646: }
                    647: 
                    648: function getIndexByName(formid,item) {
                    649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    650:         if (document.forms[formid].elements[i].name == item) {
                    651:             return i;
                    652:         }
                    653:     }
                    654:     return -1;
                    655: }
1.468     raeburn   656: 
1.876     raeburn   657: function getDomainFromSelectbox(formname,udom) {
                    658:     var userdom;
                    659:     var formid = getFormIdByName(formname);
                    660:     if (formid > -1) {
                    661:         var domid = getIndexByName(formid,udom);
                    662:         if (domid > -1) {
                    663:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    665:             }
                    666:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    667:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   668:             }
                    669:         }
                    670:     }
1.876     raeburn   671:     return userdom;
                    672: }
                    673: 
                    674: ENDJS
1.468     raeburn   675: 
1.876     raeburn   676: }
                    677: 
1.1017    raeburn   678: sub javascript_array_indexof {
1.1018    raeburn   679:     return <<ENDJS;
1.1017    raeburn   680: <script type="text/javascript" language="JavaScript">
                    681: // <![CDATA[
                    682: 
                    683: if (!Array.prototype.indexOf) {
                    684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    685:         "use strict";
                    686:         if (this === void 0 || this === null) {
                    687:             throw new TypeError();
                    688:         }
                    689:         var t = Object(this);
                    690:         var len = t.length >>> 0;
                    691:         if (len === 0) {
                    692:             return -1;
                    693:         }
                    694:         var n = 0;
                    695:         if (arguments.length > 0) {
                    696:             n = Number(arguments[1]);
1.1088    foxr      697:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   698:                 n = 0;
                    699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    701:             }
                    702:         }
                    703:         if (n >= len) {
                    704:             return -1;
                    705:         }
                    706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    707:         for (; k < len; k++) {
                    708:             if (k in t && t[k] === searchElement) {
                    709:                 return k;
                    710:             }
                    711:         }
                    712:         return -1;
                    713:     }
                    714: }
                    715: 
                    716: // ]]>
                    717: </script>
                    718: 
                    719: ENDJS
                    720: 
                    721: }
                    722: 
1.876     raeburn   723: sub userbrowser_javascript {
                    724:     my $id_functions = &javascript_index_functions();
                    725:     return <<"ENDUSERBRW";
                    726: 
1.888     raeburn   727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   728:     var url = '/adm/pickuser?';
                    729:     var userdom = getDomainFromSelectbox(formname,udom);
                    730:     if (userdom != null) {
                    731:        if (userdom != '') {
                    732:            url += 'srchdom='+userdom+'&';
                    733:        }
                    734:     }
                    735:     url += 'form=' + formname + '&unameelement='+uname+
                    736:                                 '&udomelement='+udom+
                    737:                                 '&ulastelement='+ulast+
                    738:                                 '&ufirstelement='+ufirst+
                    739:                                 '&uemailelement='+uemail+
1.881     raeburn   740:                                 '&hideudomelement='+hideudom+
                    741:                                 '&coursedom='+crsdom;
1.888     raeburn   742:     if ((caller != null) && (caller != undefined)) {
                    743:         url += '&caller='+caller;
                    744:     }
1.876     raeburn   745:     var title = 'User_Browser';
                    746:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    747:     options += ',width=700,height=600';
                    748:     var stdeditbrowser = open(url,title,options,'1');
                    749:     stdeditbrowser.focus();
                    750: }
                    751: 
1.888     raeburn   752: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   753:     var formid = getFormIdByName(formname);
                    754:     if (formid > -1) {
1.888     raeburn   755:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   756:         var domid = getIndexByName(formid,udom);
                    757:         var hidedomid = getIndexByName(formid,origdom);
                    758:         if (hidedomid > -1) {
                    759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   760:             var unameval = document.forms[formid].elements[unameid].value;
                    761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    762:                 if (domid > -1) {
                    763:                     var slct = document.forms[formid].elements[domid];
                    764:                     if (slct.type == 'select-one') {
                    765:                         var i;
                    766:                         for (i=0;i<slct.length;i++) {
                    767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    768:                         }
                    769:                     }
                    770:                     if (slct.type == 'hidden') {
                    771:                         slct.value = fixeddom;
1.876     raeburn   772:                     }
                    773:                 }
1.468     raeburn   774:             }
                    775:         }
                    776:     }
1.876     raeburn   777:     return;
                    778: }
                    779: 
                    780: $id_functions
                    781: ENDUSERBRW
1.468     raeburn   782: }
                    783: 
                    784: sub setsec_javascript {
1.1116    raeburn   785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    787:         $communityrolestr);
                    788:     if ($role_element ne '') {
                    789:         my @allroles = ('st','ta','ep','in','ad');
                    790:         foreach my $crstype ('Course','Community') {
                    791:             if ($crstype eq 'Community') {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    796:             } else {
                    797:                 foreach my $role (@allroles) {
                    798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    799:                 }
                    800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    801:             }
                    802:         }
                    803:         $rolestr = '"'.join('","',@allroles).'"';
                    804:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    806:     }
1.468     raeburn   807:     my $setsections = qq|
                    808: function setSect(sectionlist) {
1.629     raeburn   809:     var sectionsArray = new Array();
                    810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    811:         sectionsArray = sectionlist.split(",");
                    812:     }
1.468     raeburn   813:     var numSections = sectionsArray.length;
                    814:     document.$formname.$sec_element.length = 0;
                    815:     if (numSections == 0) {
                    816:         document.$formname.$sec_element.multiple=false;
                    817:         document.$formname.$sec_element.size=1;
                    818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    819:     } else {
                    820:         if (numSections == 1) {
                    821:             document.$formname.$sec_element.multiple=false;
                    822:             document.$formname.$sec_element.size=1;
                    823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    826:         } else {
                    827:             for (var i=0; i<numSections; i++) {
                    828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    829:             }
                    830:             document.$formname.$sec_element.multiple=true
                    831:             if (numSections < 3) {
                    832:                 document.$formname.$sec_element.size=numSections;
                    833:             } else {
                    834:                 document.$formname.$sec_element.size=3;
                    835:             }
                    836:             document.$formname.$sec_element.options[0].selected = false
                    837:         }
                    838:     }
1.91      www       839: }
1.905     raeburn   840: 
                    841: function setRole(crstype) {
1.468     raeburn   842: |;
1.905     raeburn   843:     if ($role_element eq '') {
                    844:         $setsections .= '    return;
                    845: }
                    846: ';
                    847:     } else {
                    848:         $setsections .= qq|
                    849:     var elementLength = document.$formname.$role_element.length;
                    850:     var allroles = Array($rolestr);
                    851:     var courserolenames = Array($courserolestr);
                    852:     var communityrolenames = Array($communityrolestr);
                    853:     if (elementLength != undefined) {
                    854:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    855:             if (crstype == 'Course') {
                    856:                 return;
                    857:             } else {
                    858:                 allroles[5] = 'co';
                    859:                 for (var i=0; i<6; i++) {
                    860:                     document.$formname.$role_element.options[i].value = allroles[i];
                    861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    862:                 }
                    863:             }
                    864:         } else {
                    865:             if (crstype == 'Community') {
                    866:                 return;
                    867:             } else {
                    868:                 allroles[5] = 'cc';
                    869:                 for (var i=0; i<6; i++) {
                    870:                     document.$formname.$role_element.options[i].value = allroles[i];
                    871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    872:                 }
                    873:             }
                    874:         }
                    875:     }
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.1116    raeburn   880:     if ($credits_element) {
                    881:         $setsections .= qq|
                    882: function setCredits(defaultcredits) {
                    883:     document.$formname.$credits_element.value = defaultcredits;
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.468     raeburn   888:     return $setsections;
                    889: }
                    890: 
1.91      www       891: sub selectcourse_link {
1.909     raeburn   892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    893:        $typeelement) = @_;
                    894:    my $type = $selecttype;
1.871     raeburn   895:    my $linktext = &mt('Select Course');
                    896:    if ($selecttype eq 'Community') {
1.909     raeburn   897:        $linktext = &mt('Select Community');
1.1239    raeburn   898:    } elsif ($selecttype eq 'Placement') {
                    899:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   935:             if (!field[i].disabled) { 
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1093    raeburn   940:         if (!field.disabled) { 
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1256    raeburn   960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1256    raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1241    raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1241    raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1220    raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1015:                 push(@possibles,$id);
                   1016:             } 
1.687     raeburn  1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1256    raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1117    raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1117    raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.1088    foxr     1052: 
                   1053: =item * &list_languages()
                   1054: 
                   1055: Returns an array reference that is suitable for use in language prompters.
                   1056: Each array element is itself a two element array.  The first element
                   1057: is the language code.  The second element a descsriptiuon of the 
                   1058: language itself.  This is suitable for use in e.g.
                   1059: &Apache::edit::select_arg (once dereferenced that is).
                   1060: 
                   1061: =cut 
                   1062: 
                   1063: sub list_languages {
                   1064:     my @lang_choices;
                   1065: 
                   1066:     foreach my $id (&languageids()) {
                   1067: 	my $code = &supportedlanguagecode($id);
                   1068: 	if ($code) {
                   1069: 	    my $selector    = $supported_codes{$id};
                   1070: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1071: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1072: 	}
                   1073:     }
                   1074:     return \@lang_choices;
                   1075: }
                   1076: 
                   1077: =pod
                   1078: 
1.648     raeburn  1079: =item * &linked_select_forms(...)
1.36      matthew  1080: 
                   1081: linked_select_forms returns a string containing a <script></script> block
                   1082: and html for two <select> menus.  The select menus will be linked in that
                   1083: changing the value of the first menu will result in new values being placed
                   1084: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1085: order unless a defined order is provided.
1.36      matthew  1086: 
                   1087: linked_select_forms takes the following ordered inputs:
                   1088: 
                   1089: =over 4
                   1090: 
1.112     bowersj2 1091: =item * $formname, the name of the <form> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $firstdefault, the default value for the first menu
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1102: 
1.609     raeburn  1103: =item * $menuorder, the order of values in the first menu
                   1104: 
1.1115    raeburn  1105: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1106:         event for the first <select> tag
                   1107: 
                   1108: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1109:         event for the second <select> tag
                   1110: 
1.1245    raeburn  1111: =item * $suffix, to differentiate separate uses of select2data javascript
                   1112:         objects in a page.
                   1113: 
1.41      ng       1114: =back 
                   1115: 
1.36      matthew  1116: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1118: values for the first select menu.  The text that coincides with the 
1.41      ng       1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1120: and text for the second menu are given in the hash pointed to by 
                   1121: $menu{$choice1}->{'select2'}.  
                   1122: 
1.112     bowersj2 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1124:                        default => "B3",
                   1125:                        select2 => { 
                   1126:                            B1 => "Choice B1",
                   1127:                            B2 => "Choice B2",
                   1128:                            B3 => "Choice B3",
                   1129:                            B4 => "Choice B4"
1.609     raeburn  1130:                            },
                   1131:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1132:                    },
                   1133:                A2 => { text =>"Choice A2" ,
                   1134:                        default => "C2",
                   1135:                        select2 => { 
                   1136:                            C1 => "Choice C1",
                   1137:                            C2 => "Choice C2",
                   1138:                            C3 => "Choice C3"
1.609     raeburn  1139:                            },
                   1140:                        order => ['C2','C1','C3'],
1.112     bowersj2 1141:                    },
                   1142:                A3 => { text =>"Choice A3" ,
                   1143:                        default => "D6",
                   1144:                        select2 => { 
                   1145:                            D1 => "Choice D1",
                   1146:                            D2 => "Choice D2",
                   1147:                            D3 => "Choice D3",
                   1148:                            D4 => "Choice D4",
                   1149:                            D5 => "Choice D5",
                   1150:                            D6 => "Choice D6",
                   1151:                            D7 => "Choice D7"
1.609     raeburn  1152:                            },
                   1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1154:                    }
                   1155:                );
1.36      matthew  1156: 
                   1157: =cut
                   1158: 
                   1159: sub linked_select_forms {
                   1160:     my ($formname,
                   1161:         $middletext,
                   1162:         $firstdefault,
                   1163:         $firstselectname,
                   1164:         $secondselectname, 
1.609     raeburn  1165:         $hashref,
                   1166:         $menuorder,
1.1115    raeburn  1167:         $onchangefirst,
1.1245    raeburn  1168:         $onchangesecond,
                   1169:         $suffix
1.36      matthew  1170:         ) = @_;
                   1171:     my $second = "document.$formname.$secondselectname";
                   1172:     my $first = "document.$formname.$firstselectname";
                   1173:     # output the javascript to do the changing
                   1174:     my $result = '';
1.776     bisitz   1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1176:     $result.="// <![CDATA[\n";
1.1245    raeburn  1177:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1178:     $" = '","';
                   1179:     my $debug = '';
                   1180:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1183:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1187:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1188:         }
1.36      matthew  1189:         $result.="\"@s2values\");\n";
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1191:         my @s2texts;
                   1192:         foreach my $value (@s2values) {
1.1263    raeburn  1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1194:         }
                   1195:         $result.="\"@s2texts\");\n";
                   1196:     }
                   1197:     $"=' ';
                   1198:     $result.= <<"END";
                   1199: 
1.1245    raeburn  1200: function select1${suffix}_changed() {
1.36      matthew  1201:     // Determine new choice
1.1245    raeburn  1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1203:     // update select2
1.1245    raeburn  1204:     var values     = select2data${suffix}[newvalue].values;
                   1205:     var texts      = select2data${suffix}[newvalue].texts;
                   1206:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1207:     var i;
                   1208:     // out with the old
1.1245    raeburn  1209:     $second.options.length = 0;
                   1210:     // in with the new
1.36      matthew  1211:     for (i=0;i<values.length; i++) {
                   1212:         $second.options[i] = new Option(values[i]);
1.143     matthew  1213:         $second.options[i].value = values[i];
1.36      matthew  1214:         $second.options[i].text = texts[i];
                   1215:         if (values[i] == select2def) {
                   1216:             $second.options[i].selected = true;
                   1217:         }
                   1218:     }
                   1219: }
1.824     bisitz   1220: // ]]>
1.36      matthew  1221: </script>
                   1222: END
                   1223:     # output the initial values for the selection lists
1.1245    raeburn  1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1225:     my @order = sort(keys(%{$hashref}));
                   1226:     if (ref($menuorder) eq 'ARRAY') {
                   1227:         @order = @{$menuorder};
                   1228:     }
                   1229:     foreach my $value (@order) {
1.36      matthew  1230:         $result.="    <option value=\"$value\" ";
1.253     albertel 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1233:     }
                   1234:     $result .= "</select>\n";
                   1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1236:     $result .= $middletext;
1.1115    raeburn  1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1238:     if ($onchangesecond) {
                   1239:         $result .= ' onchange="'.$onchangesecond.'"';
                   1240:     }
                   1241:     $result .= ">\n";
1.36      matthew  1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1243:     
                   1244:     my @secondorder = sort(keys(%select2));
                   1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1247:     }
                   1248:     foreach my $value (@secondorder) {
1.36      matthew  1249:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1251:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1252:     }
                   1253:     $result .= "</select>\n";
                   1254:     #    return $debug;
                   1255:     return $result;
                   1256: }   #  end of sub linked_select_forms {
                   1257: 
1.45      matthew  1258: =pod
1.44      bowersj2 1259: 
1.973     raeburn  1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1261: 
1.112     bowersj2 1262: Returns a string corresponding to an HTML link to the given help
                   1263: $topic, where $topic corresponds to the name of a .tex file in
                   1264: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1265: spaces. 
                   1266: 
                   1267: $text will optionally be linked to the same topic, allowing you to
                   1268: link text in addition to the graphic. If you do not want to link
                   1269: text, but wish to specify one of the later parameters, pass an
                   1270: empty string. 
                   1271: 
                   1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1273: the link will not open a new window. If false, the link will open
                   1274: a new window using Javascript. (Default is false.) 
                   1275: 
                   1276: $width and $height are optional numerical parameters that will
                   1277: override the width and height of the popped up window, which may
1.973     raeburn  1278: be useful for certain help topics with big pictures included.
                   1279: 
                   1280: $imgid is the id of the img tag used for the help icon. This may be
                   1281: used in a javascript call to switch the image src.  See 
                   1282: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1283: 
                   1284: =cut
                   1285: 
                   1286: sub help_open_topic {
1.973     raeburn  1287:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1288:     $text = "" if (not defined $text);
1.44      bowersj2 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1290:     $width = 500 if (not defined $width);
1.44      bowersj2 1291:     $height = 400 if (not defined $height);
                   1292:     my $filename = $topic;
                   1293:     $filename =~ s/ /_/g;
                   1294: 
1.48      bowersj2 1295:     my $template = "";
                   1296:     my $link;
1.572     banghart 1297:     
1.159     www      1298:     $topic=~s/\W/\_/g;
1.44      bowersj2 1299: 
1.572     banghart 1300:     if (!$stayOnPage) {
1.1033    www      1301: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1302:     } elsif ($stayOnPage eq 'popup') {
                   1303:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1304:     } else {
1.48      bowersj2 1305: 	$link = "/adm/help/${filename}.hlp";
                   1306:     }
                   1307: 
                   1308:     # Add the text
1.1314    raeburn  1309:     my $target = ' target="_top"';
                   1310:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1311:         $target = '';
                   1312:     }
1.755     neumanie 1313:     if ($text ne "") {	
1.763     bisitz   1314: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1315:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1316:                   .$text.'</a>';
1.48      bowersj2 1317:     }
                   1318: 
1.763     bisitz   1319:     # (Always) Add the graphic
1.179     matthew  1320:     my $title = &mt('Online Help');
1.667     raeburn  1321:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1322:     if ($imgid ne '') {
                   1323:         $imgid = ' id="'.$imgid.'"';
                   1324:     }
1.1314    raeburn  1325:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1326:               .'<img src="'.$helpicon.'" border="0"'
                   1327:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1328:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1329:               .' /></a>';
                   1330:     if ($text ne "") {	
                   1331:         $template.='</span>';
                   1332:     }
1.44      bowersj2 1333:     return $template;
                   1334: 
1.106     bowersj2 1335: }
                   1336: 
                   1337: # This is a quicky function for Latex cheatsheet editing, since it 
                   1338: # appears in at least four places
                   1339: sub helpLatexCheatsheet {
1.1037    www      1340:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1341:     my $out;
1.106     bowersj2 1342:     my $addOther = '';
1.732     raeburn  1343:     if ($topic) {
1.1037    www      1344: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1345:     }
                   1346:     $out = '<span>' # Start cheatsheet
                   1347: 	  .$addOther
                   1348:           .'<span>'
1.1037    www      1349: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1350: 	  .'</span> <span>'
1.1037    www      1351: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1352: 	  .'</span>';
1.732     raeburn  1353:     unless ($not_author) {
1.1186    kruse    1354:         $out .= '<span>'
                   1355:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1356:                .'</span> <span>'
                   1357:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1358: 	       .'</span>';
1.732     raeburn  1359:     }
1.763     bisitz   1360:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1361:     return $out;
1.172     www      1362: }
                   1363: 
1.430     albertel 1364: sub general_help {
                   1365:     my $helptopic='Student_Intro';
                   1366:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1367: 	$helptopic='Authoring_Intro';
1.907     raeburn  1368:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1369: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1370:     } elsif ($env{'request.role'}=~/^dc/) {
                   1371:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1372:     }
                   1373:     return $helptopic;
                   1374: }
                   1375: 
                   1376: sub update_help_link {
                   1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1378:     my $origurl = $ENV{'REQUEST_URI'};
                   1379:     $origurl=~s|^/~|/priv/|;
                   1380:     my $timestamp = time;
                   1381:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1382:         $$datum = &escape($$datum);
                   1383:     }
                   1384: 
                   1385:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1386:     my $output .= <<"ENDOUTPUT";
                   1387: <script type="text/javascript">
1.824     bisitz   1388: // <![CDATA[
1.430     albertel 1389: banner_link = '$banner_link';
1.824     bisitz   1390: // ]]>
1.430     albertel 1391: </script>
                   1392: ENDOUTPUT
                   1393:     return $output;
                   1394: }
                   1395: 
                   1396: # now just updates the help link and generates a blue icon
1.193     raeburn  1397: sub help_open_menu {
1.430     albertel 1398:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1399: 	= @_;    
1.949     droeschl 1400:     $stayOnPage = 1;
1.430     albertel 1401:     my $output;
                   1402:     if ($component_help) {
                   1403: 	if (!$text) {
                   1404: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1405: 				       $width,$height);
                   1406: 	} else {
                   1407: 	    my $help_text;
                   1408: 	    $help_text=&unescape($topic);
                   1409: 	    $output='<table><tr><td>'.
                   1410: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1411: 				 $width,$height).'</td></tr></table>';
                   1412: 	}
                   1413:     }
                   1414:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1415:     return $output.$banner_link;
                   1416: }
                   1417: 
                   1418: sub top_nav_help {
1.1369    raeburn  1419:     my ($text,$linkattr) = @_;
1.436     albertel 1420:     $text = &mt($text);
1.949     droeschl 1421:     my $stay_on_page = 1;
                   1422: 
1.1168    raeburn  1423:     my ($link,$banner_link);
                   1424:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1425:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1426: 	                         : "javascript:helpMenu('open')";
                   1427:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1428:     }
1.201     raeburn  1429:     my $title = &mt('Get help');
1.1168    raeburn  1430:     if ($link) {
                   1431:         return <<"END";
1.436     albertel 1432: $banner_link
1.1369    raeburn  1433: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1434: END
1.1168    raeburn  1435:     } else {
                   1436:         return '&nbsp;'.$text.'&nbsp;';
                   1437:     }
1.436     albertel 1438: }
                   1439: 
                   1440: sub help_menu_js {
1.1154    raeburn  1441:     my ($httphost) = @_;
1.949     droeschl 1442:     my $stayOnPage = 1;
1.436     albertel 1443:     my $width = 620;
                   1444:     my $height = 600;
1.430     albertel 1445:     my $helptopic=&general_help();
1.1154    raeburn  1446:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1447:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1448:     my $start_page =
                   1449:         &Apache::loncommon::start_page('Help Menu', undef,
                   1450: 				       {'frameset'    => 1,
                   1451: 					'js_ready'    => 1,
1.1154    raeburn  1452:                                         'use_absolute' => $httphost,
1.331     albertel 1453: 					'add_entries' => {
1.1168    raeburn  1454: 					    'border' => '0', 
1.579     raeburn  1455: 					    'rows'   => "110,*",},});
1.331     albertel 1456:     my $end_page =
                   1457:         &Apache::loncommon::end_page({'frameset' => 1,
                   1458: 				      'js_ready' => 1,});
                   1459: 
1.436     albertel 1460:     my $template .= <<"ENDTEMPLATE";
                   1461: <script type="text/javascript">
1.877     bisitz   1462: // <![CDATA[
1.253     albertel 1463: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1464: var banner_link = '';
1.243     raeburn  1465: function helpMenu(target) {
                   1466:     var caller = this;
                   1467:     if (target == 'open') {
                   1468:         var newWindow = null;
                   1469:         try {
1.262     albertel 1470:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1471:         }
                   1472:         catch(error) {
                   1473:             writeHelp(caller);
                   1474:             return;
                   1475:         }
                   1476:         if (newWindow) {
                   1477:             caller = newWindow;
                   1478:         }
1.193     raeburn  1479:     }
1.243     raeburn  1480:     writeHelp(caller);
                   1481:     return;
                   1482: }
                   1483: function writeHelp(caller) {
1.1168    raeburn  1484:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1485:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1486:     caller.document.close();
                   1487:     caller.focus();
1.193     raeburn  1488: }
1.877     bisitz   1489: // END LON-CAPA Internal -->
1.253     albertel 1490: // ]]>
1.436     albertel 1491: </script>
1.193     raeburn  1492: ENDTEMPLATE
                   1493:     return $template;
                   1494: }
                   1495: 
1.172     www      1496: sub help_open_bug {
                   1497:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1498:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1499:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1500:     $text = "" if (not defined $text);
                   1501: 	$stayOnPage=1;
1.184     albertel 1502:     $width = 600 if (not defined $width);
                   1503:     $height = 600 if (not defined $height);
1.172     www      1504: 
                   1505:     $topic=~s/\W+/\+/g;
                   1506:     my $link='';
                   1507:     my $template='';
1.379     albertel 1508:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1509: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1510:     if (!$stayOnPage)
                   1511:     {
                   1512: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1513:     }
                   1514:     else
                   1515:     {
                   1516: 	$link = $url;
                   1517:     }
1.1314    raeburn  1518: 
                   1519:     my $target = ' target="_top"';
                   1520:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1521:         $target = '';
                   1522:     }
1.172     www      1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
                   1527:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1528:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('Report a Bug');
1.215     albertel 1533:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1535:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
                   1540: }
                   1541: 
                   1542: sub help_open_faq {
                   1543:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1544:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1545:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1546:     $text = "" if (not defined $text);
                   1547: 	$stayOnPage=1;
                   1548:     $width = 350 if (not defined $width);
                   1549:     $height = 400 if (not defined $height);
                   1550: 
                   1551:     $topic=~s/\W+/\+/g;
                   1552:     my $link='';
                   1553:     my $template='';
                   1554:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1555:     if (!$stayOnPage)
                   1556:     {
                   1557: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1558:     }
                   1559:     else
                   1560:     {
                   1561: 	$link = $url;
                   1562:     }
                   1563: 
                   1564:     # Add the text
                   1565:     if ($text ne "")
                   1566:     {
                   1567: 	$template .= 
1.173     www      1568:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1569:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1570:     }
                   1571: 
                   1572:     # Add the graphic
1.179     matthew  1573:     my $title = &mt('View the FAQ');
1.215     albertel 1574:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1575:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1576:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1577: ENDTEMPLATE
                   1578:     if ($text ne '') { $template.='</td></tr></table>' };
                   1579:     return $template;
                   1580: 
1.44      bowersj2 1581: }
1.37      matthew  1582: 
1.180     matthew  1583: ###############################################################
                   1584: ###############################################################
                   1585: 
1.45      matthew  1586: =pod
                   1587: 
1.648     raeburn  1588: =item * &change_content_javascript():
1.256     matthew  1589: 
                   1590: This and the next function allow you to create small sections of an
                   1591: otherwise static HTML page that you can update on the fly with
                   1592: Javascript, even in Netscape 4.
                   1593: 
                   1594: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1595: must be written to the HTML page once. It will prove the Javascript
                   1596: function "change(name, content)". Calling the change function with the
                   1597: name of the section 
                   1598: you want to update, matching the name passed to C<changable_area>, and
                   1599: the new content you want to put in there, will put the content into
                   1600: that area.
                   1601: 
                   1602: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1603: to contain room for the original contents. You need to "make space"
                   1604: for whatever changes you wish to make, and be B<sure> to check your
                   1605: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1606: it's adequate for updating a one-line status display, but little more.
                   1607: This script will set the space to 100% width, so you only need to
                   1608: worry about height in Netscape 4.
                   1609: 
                   1610: Modern browsers are much less limiting, and if you can commit to the
                   1611: user not using Netscape 4, this feature may be used freely with
                   1612: pretty much any HTML.
                   1613: 
                   1614: =cut
                   1615: 
                   1616: sub change_content_javascript {
                   1617:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1618:     if ($env{'browser.type'} eq 'netscape' &&
                   1619: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1620: 	return (<<NETSCAPE4);
                   1621: 	function change(name, content) {
                   1622: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1623: 	    doc.open();
                   1624: 	    doc.write(content);
                   1625: 	    doc.close();
                   1626: 	}
                   1627: NETSCAPE4
                   1628:     } else {
                   1629: 	# Otherwise, we need to use semi-standards-compliant code
                   1630: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1631: 	# is really scary, and every useful browser supports it
                   1632: 	return (<<DOMBASED);
                   1633: 	function change(name, content) {
                   1634: 	    element = document.getElementById(name);
                   1635: 	    element.innerHTML = content;
                   1636: 	}
                   1637: DOMBASED
                   1638:     }
                   1639: }
                   1640: 
                   1641: =pod
                   1642: 
1.648     raeburn  1643: =item * &changable_area($name,$origContent):
1.256     matthew  1644: 
                   1645: This provides a "changable area" that can be modified on the fly via
                   1646: the Javascript code provided in C<change_content_javascript>. $name is
                   1647: the name you will use to reference the area later; do not repeat the
                   1648: same name on a given HTML page more then once. $origContent is what
                   1649: the area will originally contain, which can be left blank.
                   1650: 
                   1651: =cut
                   1652: 
                   1653: sub changable_area {
                   1654:     my ($name, $origContent) = @_;
                   1655: 
1.258     albertel 1656:     if ($env{'browser.type'} eq 'netscape' &&
                   1657: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1658: 	# If this is netscape 4, we need to use the Layer tag
                   1659: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1660:     } else {
                   1661: 	return "<span id='$name'>$origContent</span>";
                   1662:     }
                   1663: }
                   1664: 
                   1665: =pod
                   1666: 
1.648     raeburn  1667: =item * &viewport_geometry_js 
1.590     raeburn  1668: 
                   1669: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: 
                   1674: sub viewport_geometry_js { 
                   1675:     return <<"GEOMETRY";
                   1676: var Geometry = {};
                   1677: function init_geometry() {
                   1678:     if (Geometry.init) { return };
                   1679:     Geometry.init=1;
                   1680:     if (window.innerHeight) {
                   1681:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1682:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1683:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1684:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1685:     }
                   1686:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1687:         Geometry.getViewportHeight =
                   1688:             function() { return document.documentElement.clientHeight; };
                   1689:         Geometry.getViewportWidth =
                   1690:             function() { return document.documentElement.clientWidth; };
                   1691: 
                   1692:         Geometry.getHorizontalScroll =
                   1693:             function() { return document.documentElement.scrollLeft; };
                   1694:         Geometry.getVerticalScroll =
                   1695:             function() { return document.documentElement.scrollTop; };
                   1696:     }
                   1697:     else if (document.body.clientHeight) {
                   1698:         Geometry.getViewportHeight =
                   1699:             function() { return document.body.clientHeight; };
                   1700:         Geometry.getViewportWidth =
                   1701:             function() { return document.body.clientWidth; };
                   1702:         Geometry.getHorizontalScroll =
                   1703:             function() { return document.body.scrollLeft; };
                   1704:         Geometry.getVerticalScroll =
                   1705:             function() { return document.body.scrollTop; };
                   1706:     }
                   1707: }
                   1708: 
                   1709: GEOMETRY
                   1710: }
                   1711: 
                   1712: =pod
                   1713: 
1.648     raeburn  1714: =item * &viewport_size_js()
1.590     raeburn  1715: 
                   1716: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1717: 
                   1718: =cut
                   1719: 
                   1720: sub viewport_size_js {
                   1721:     my $geometry = &viewport_geometry_js();
                   1722:     return <<"DIMS";
                   1723: 
                   1724: $geometry
                   1725: 
                   1726: function getViewportDims(width,height) {
                   1727:     init_geometry();
                   1728:     width.value = Geometry.getViewportWidth();
                   1729:     height.value = Geometry.getViewportHeight();
                   1730:     return;
                   1731: }
                   1732: 
                   1733: DIMS
                   1734: }
                   1735: 
                   1736: =pod
                   1737: 
1.648     raeburn  1738: =item * &resize_textarea_js()
1.565     albertel 1739: 
                   1740: emits the needed javascript to resize a textarea to be as big as possible
                   1741: 
                   1742: creates a function resize_textrea that takes two IDs first should be
                   1743: the id of the element to resize, second should be the id of a div that
                   1744: surrounds everything that comes after the textarea, this routine needs
                   1745: to be attached to the <body> for the onload and onresize events.
                   1746: 
1.648     raeburn  1747: =back
1.565     albertel 1748: 
                   1749: =cut
                   1750: 
                   1751: sub resize_textarea_js {
1.590     raeburn  1752:     my $geometry = &viewport_geometry_js();
1.565     albertel 1753:     return <<"RESIZE";
                   1754:     <script type="text/javascript">
1.824     bisitz   1755: // <![CDATA[
1.590     raeburn  1756: $geometry
1.565     albertel 1757: 
1.588     albertel 1758: function getX(element) {
                   1759:     var x = 0;
                   1760:     while (element) {
                   1761: 	x += element.offsetLeft;
                   1762: 	element = element.offsetParent;
                   1763:     }
                   1764:     return x;
                   1765: }
                   1766: function getY(element) {
                   1767:     var y = 0;
                   1768:     while (element) {
                   1769: 	y += element.offsetTop;
                   1770: 	element = element.offsetParent;
                   1771:     }
                   1772:     return y;
                   1773: }
                   1774: 
                   1775: 
1.565     albertel 1776: function resize_textarea(textarea_id,bottom_id) {
                   1777:     init_geometry();
                   1778:     var textarea        = document.getElementById(textarea_id);
                   1779:     //alert(textarea);
                   1780: 
1.588     albertel 1781:     var textarea_top    = getY(textarea);
1.565     albertel 1782:     var textarea_height = textarea.offsetHeight;
                   1783:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1784:     var bottom_top      = getY(bottom);
1.565     albertel 1785:     var bottom_height   = bottom.offsetHeight;
                   1786:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1787:     var fudge           = 23;
1.565     albertel 1788:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1789:     if (new_height < 300) {
                   1790: 	new_height = 300;
                   1791:     }
                   1792:     textarea.style.height=new_height+'px';
                   1793: }
1.824     bisitz   1794: // ]]>
1.565     albertel 1795: </script>
                   1796: RESIZE
                   1797: 
                   1798: }
                   1799: 
1.1205    golterma 1800: sub colorfuleditor_js {
1.1248    raeburn  1801:     my $browse_or_search;
                   1802:     my $respath;
                   1803:     my ($cnum,$cdom) = &crsauthor_url();
                   1804:     if ($cnum) {
                   1805:         $respath = "/res/$cdom/$cnum/";
                   1806:         my %js_lt = &Apache::lonlocal::texthash(
                   1807:             sunm => 'Sub-directory name',
                   1808:             save => 'Save page to make this permanent',
                   1809:         );
                   1810:         &js_escape(\%js_lt);
                   1811:         $browse_or_search = <<"END";
                   1812: 
                   1813:     function toggleChooser(form,element,titleid,only,search) {
                   1814:         var disp = 'none';
                   1815:         if (document.getElementById('chooser_'+element)) {
                   1816:             var curr = document.getElementById('chooser_'+element).style.display;
                   1817:             if (curr == 'none') {
                   1818:                 disp='inline';
                   1819:                 if (form.elements['chooser_'+element].length) {
                   1820:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1821:                         form.elements['chooser_'+element][i].checked = false;
                   1822:                     }
                   1823:                 }
                   1824:                 toggleResImport(form,element);
                   1825:             }
                   1826:             document.getElementById('chooser_'+element).style.display = disp;
                   1827:         }
                   1828:     }
                   1829: 
                   1830:     function toggleCrsFile(form,element,numdirs) {
                   1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1832:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1833:             if (curr == 'none') {
                   1834:                 if (numdirs) {
                   1835:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1836:                     if (numdirs > 1) {
                   1837:                         window['select1'+element+'_changed']();
                   1838:                     }
                   1839:                 }
                   1840:             } 
                   1841:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1842:             
                   1843:         }
                   1844:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1845:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1846:             if (document.getElementById('uploadcrsres_'+element)) {
                   1847:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1848:             }
                   1849:         }
                   1850:         return;
                   1851:     }
                   1852: 
                   1853:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1854:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1855:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1856:         }
                   1857:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1858:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1859:             if (curr == 'none') {
                   1860:                 if (numcrsdirs) {
                   1861:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1862:                    form.elements['newsubdir_'+element][0].checked = true;
                   1863:                    toggleNewsubdir(form,element);
                   1864:                 }
                   1865:             }
                   1866:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1867:         }
                   1868:         return;
                   1869:     }
                   1870: 
                   1871:     function toggleResImport(form,element) {
                   1872:         var choices = new Array('crsres','upload');
                   1873:         for (var i=0; i<choices.length; i++) {
                   1874:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1875:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1876:             }
                   1877:         }
                   1878:     }
                   1879: 
                   1880:     function toggleNewsubdir(form,element) {
                   1881:         var newsub = form.elements['newsubdir_'+element];
                   1882:         if (newsub) {
                   1883:             if (newsub.length) {
                   1884:                 for (var j=0; j<newsub.length; j++) {
                   1885:                     if (newsub[j].checked) {
                   1886:                         if (document.getElementById('newsubdirname_'+element)) {
                   1887:                             if (newsub[j].value == '1') {
                   1888:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1889:                                 if (document.getElementById('newsubdir_'+element)) {
                   1890:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1891:                                 }
                   1892:                             } else {
                   1893:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1894:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1895:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1896:                             }
                   1897:                         }
                   1898:                         break; 
                   1899:                     }
                   1900:                 }
                   1901:             }
                   1902:         }
                   1903:     }
                   1904: 
                   1905:     function updateCrsFile(form,element) {
                   1906:         var directory = form.elements['coursepath_'+element];
                   1907:         var filename = form.elements['coursefile_'+element];
                   1908:         var path = directory.options[directory.selectedIndex].value;
                   1909:         var file = filename.options[filename.selectedIndex].value;
                   1910:         form.elements[element].value = '$respath';
                   1911:         if (path == '/') {
                   1912:             form.elements[element].value += file;
                   1913:         } else {
                   1914:             form.elements[element].value += path+'/'+file;
                   1915:         }
                   1916:         unClean();
                   1917:         if (document.getElementById('previewimg_'+element)) {
                   1918:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1919:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1920:         }
                   1921:         if (document.getElementById('showimg_'+element)) {
                   1922:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1923:         }
                   1924:         toggleChooser(form,element);
                   1925:         return;
                   1926:     }
                   1927: 
                   1928:     function uploadDone(suffix,name) {
                   1929:         if (name) {
                   1930: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1931:             unClean();
                   1932:             toggleChooser(document.forms["lonhomework"],suffix);
                   1933:         }
                   1934:     }
                   1935: 
                   1936: \$(document).ready(function(){
                   1937: 
                   1938:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1939:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1940:             var buttonId = this.id;
                   1941:             var suffix = buttonId.toString();
                   1942:             suffix = suffix.replace(/^crsupload_/,'');
                   1943:             event.preventDefault();
                   1944:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1945:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1946:             \$(this.form).submit();
                   1947:             document.lonhomework.target = '';
                   1948:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1949:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1950:             }
                   1951:             return false;
                   1952:         }
                   1953:     });
                   1954: });
                   1955: END
                   1956:     }
1.1205    golterma 1957:     return <<"COLORFULEDIT"
                   1958: <script type="text/javascript">
                   1959: // <![CDATA[>
                   1960:     function fold_box(curDepth, lastresource){
                   1961: 
                   1962:     // we need a list because there can be several blocks you need to fold in one tag
                   1963:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1964:     // but there is only one folding button per tag
                   1965:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1966: 
                   1967:         if(block.item(0).style.display == 'none'){
                   1968: 
                   1969:             foldbutton.value = '@{[&mt("Hide")]}';
                   1970:             for (i = 0; i < block.length; i++){
                   1971:                 block.item(i).style.display = '';
                   1972:             }
                   1973:         }else{
                   1974: 
                   1975:             foldbutton.value = '@{[&mt("Show")]}';
                   1976:             for (i = 0; i < block.length; i++){
                   1977:                 // block.item(i).style.visibility = 'collapse';
                   1978:                 block.item(i).style.display = 'none';
                   1979:             }
                   1980:         };
                   1981:         saveState(lastresource);
                   1982:     }
                   1983: 
                   1984:     function saveState (lastresource) {
                   1985: 
                   1986:         var tag_list = getTagList();
                   1987:         if(tag_list != null){
                   1988:             var timestamp = new Date().getTime();
                   1989:             var key = lastresource;
                   1990: 
                   1991:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1992:             // starting with timestamp
                   1993:             var value = timestamp+';';
                   1994: 
                   1995:             // building the list of key-value pairs
                   1996:             for(var i = 0; i < tag_list.length; i++){
                   1997:                 value += tag_list[i]+',';
                   1998:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1999:             }
                   2000: 
                   2001:             // only iterate whole storage if nothing to override
                   2002:             if(localStorage.getItem(key) == null){        
                   2003: 
                   2004:                 // prevent storage from growing large
                   2005:                 if(localStorage.length > 50){
                   2006:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2007:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2008:                     var oldest_key;
                   2009:                     
                   2010:                     for(var i = 1; i < localStorage.length; i++){
                   2011:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2012:                             oldest_key = localStorage.key(i);
                   2013:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2014:                         }
                   2015:                     }
                   2016:                     localStorage.removeItem(oldest_key);
                   2017:                 }
                   2018:             }
                   2019:             localStorage.setItem(key,value);
                   2020:         }
                   2021:     }
                   2022: 
                   2023:     // restore folding status of blocks (on page load)
                   2024:     function restoreState (lastresource) {
                   2025:         if(localStorage.getItem(lastresource) != null){
                   2026:             var key = lastresource;
                   2027:             var value = localStorage.getItem(key);
                   2028:             var regex_delTimestamp = /^\d+;/;
                   2029: 
                   2030:             value.replace(regex_delTimestamp, '');
                   2031: 
                   2032:             var valueArr = value.split(';');
                   2033:             var pairs;
                   2034:             var elements;
                   2035:             for (var i = 0; i < valueArr.length; i++){
                   2036:                 pairs = valueArr[i].split(',');
                   2037:                 elements = document.getElementsByName(pairs[0]);
                   2038: 
                   2039:                 for (var j = 0; j < elements.length; j++){  
                   2040:                     elements[j].style.display = pairs[1];
                   2041:                     if (pairs[1] == "none"){
                   2042:                         var regex_id = /([_\\d]+)\$/;
                   2043:                         regex_id.exec(pairs[0]);
                   2044:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2045:                     }
                   2046:                 }
                   2047:             }
                   2048:         }
                   2049:     }
                   2050: 
                   2051:     function getTagList () {
                   2052:         
                   2053:         var stringToSearch = document.lonhomework.innerHTML;
                   2054: 
                   2055:         var ret = new Array();
                   2056:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2057:         var tag_list = stringToSearch.match(regex_findBlock);
                   2058: 
                   2059:         if(tag_list != null){
                   2060:             for(var i = 0; i < tag_list.length; i++){            
                   2061:                 ret.push(tag_list[i].replace(/"/, ''));
                   2062:             }
                   2063:         }
                   2064:         return ret;
                   2065:     }
                   2066: 
                   2067:     function saveScrollPosition (resource) {
                   2068:         var tag_list = getTagList();
                   2069: 
                   2070:         // we dont always want to jump to the first block
                   2071:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2072:         if(\$(window).scrollTop() > 170){
                   2073:             if(tag_list != null){
                   2074:                 var result;
                   2075:                 for(var i = 0; i < tag_list.length; i++){
                   2076:                     if(isElementInViewport(tag_list[i])){
                   2077:                         result += tag_list[i]+';';
                   2078:                     }
                   2079:                 }
                   2080:                 sessionStorage.setItem('anchor_'+resource, result);
                   2081:             }
                   2082:         } else {
                   2083:             // we dont need to save zero, just delete the item to leave everything tidy
                   2084:             sessionStorage.removeItem('anchor_'+resource);
                   2085:         }
                   2086:     }
                   2087: 
                   2088:     function restoreScrollPosition(resource){
                   2089: 
                   2090:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2091:         if(elem != null){
                   2092:             var tag_list = elem.split(';');
                   2093:             var elem_list;
                   2094: 
                   2095:             for(var i = 0; i < tag_list.length; i++){
                   2096:                 elem_list = document.getElementsByName(tag_list[i]);
                   2097:                 
                   2098:                 if(elem_list.length > 0){
                   2099:                     elem = elem_list[0];
                   2100:                     break;
                   2101:                 }
                   2102:             }
                   2103:             elem.scrollIntoView();
                   2104:         }
                   2105:     }
                   2106: 
                   2107:     function isElementInViewport(el) {
                   2108: 
                   2109:         // change to last element instead of first
                   2110:         var elem = document.getElementsByName(el);
                   2111:         var rect = elem[0].getBoundingClientRect();
                   2112: 
                   2113:         return (
                   2114:             rect.top >= 0 &&
                   2115:             rect.left >= 0 &&
                   2116:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2117:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2118:         );
                   2119:     }
                   2120:     
                   2121:     function autosize(depth){
                   2122:         var cmInst = window['cm'+depth];
                   2123:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2124: 
                   2125:         // is fixed size, switching to dynamic
                   2126:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2127:             cmInst.setSize("","auto");
                   2128:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2129:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2130: 
                   2131:         // is dynamic size, switching to fixed
                   2132:         } else {
                   2133:             cmInst.setSize("","300px");
                   2134:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2135:             sessionStorage.removeItem("autosized_"+depth);
                   2136:         }
                   2137:     }
                   2138: 
1.1248    raeburn  2139: $browse_or_search
1.1205    golterma 2140: 
                   2141: // ]]>
                   2142: </script>
                   2143: COLORFULEDIT
                   2144: }
                   2145: 
                   2146: sub xmleditor_js {
                   2147:     return <<XMLEDIT
                   2148: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2149: <script type="text/javascript">
                   2150: // <![CDATA[>
                   2151: 
                   2152:     function saveScrollPosition (resource) {
                   2153: 
                   2154:         var scrollPos = \$(window).scrollTop();
                   2155:         sessionStorage.setItem(resource,scrollPos);
                   2156:     }
                   2157: 
                   2158:     function restoreScrollPosition(resource){
                   2159: 
                   2160:         var scrollPos = sessionStorage.getItem(resource);
                   2161:         \$(window).scrollTop(scrollPos);
                   2162:     }
                   2163: 
                   2164:     // unless internet explorer
                   2165:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2166: 
                   2167:         \$(document).ready(function() {
                   2168:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2169:         });
                   2170:     }
                   2171: 
                   2172:     // inserts text at cursor position into codemirror (xml editor only)
                   2173:     function insertText(text){
                   2174:         cm.focus();
                   2175:         var curPos = cm.getCursor();
                   2176:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2177:     }
                   2178: // ]]>
                   2179: </script>
                   2180: XMLEDIT
                   2181: }
                   2182: 
                   2183: sub insert_folding_button {
                   2184:     my $curDepth = $Apache::lonxml::curdepth;
                   2185:     my $lastresource = $env{'request.ambiguous'};
                   2186: 
                   2187:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2188:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2189: }
                   2190: 
1.1248    raeburn  2191: sub crsauthor_url {
                   2192:     my ($url) = @_;
                   2193:     if ($url eq '') {
                   2194:         $url = $ENV{'REQUEST_URI'};
                   2195:     }
                   2196:     my ($cnum,$cdom);
                   2197:     if ($env{'request.course.id'}) {
                   2198:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2199:         if ($audom ne '' && $auname ne '') {
                   2200:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2201:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2202:                 $cnum = $auname;
                   2203:                 $cdom = $audom;
                   2204:             }
                   2205:         }
                   2206:     }
                   2207:     return ($cnum,$cdom);
                   2208: }
                   2209: 
                   2210: sub import_crsauthor_form {
1.1265    raeburn  2211:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2212:     return (0) unless ($env{'request.course.id'});
                   2213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2215:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2216:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2217:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2218:     my @ids=&Apache::lonnet::current_machine_ids();
                   2219:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2220:     
                   2221:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2222:         $is_home = 1;
                   2223:     }
                   2224:     $relpath = "/priv/$cdom/$cnum";
                   2225:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2226:     my %lt = &Apache::lonlocal::texthash (
                   2227:         fnam => 'Filename',
                   2228:         dire => 'Directory',
                   2229:     );
                   2230:     my $numdirs = scalar(keys(%files));
                   2231:     my (%possexts,$singledir,@singledirfiles);
                   2232:     if ($only) {
                   2233:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2234:     }
                   2235:     my (%nonemptydirs,$possdirs);
                   2236:     if ($numdirs > 1) {
                   2237:         my @order;
                   2238:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2239:             if (ref($files{$key}) eq 'HASH') {
                   2240:                 my $shown = $key;
                   2241:                 if ($key eq '') {
                   2242:                     $shown = '/';
                   2243:                 }
                   2244:                 my @ordered = ();
                   2245:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2246:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2247:                     if ($only) {
                   2248:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2249:                         unless ($possexts{lc($ext)}) {
                   2250:                             next;
                   2251:                         }
                   2252:                     }
                   2253:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2254:                     push(@ordered,$file);
                   2255:                 }
                   2256:                 if (@ordered) {
                   2257:                     push(@order,$key);
                   2258:                     $nonemptydirs{$key} = 1;
                   2259:                     $selimport_menus{$key}->{'text'} = $shown;
                   2260:                     $selimport_menus{$key}->{'default'} = '';
                   2261:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2262:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2263:                 }
                   2264:             }
                   2265:         }
                   2266:         $possdirs = scalar(keys(%nonemptydirs));
                   2267:         if ($possdirs > 1) {
                   2268:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2269:             $output = $lt{'dire'}.
                   2270:                       &linked_select_forms($form,'<br />'.
                   2271:                                            $lt{'fnam'},'',
                   2272:                                            $firstselectname,$secondselectname,
                   2273:                                            \%selimport_menus,\@order,
                   2274:                                            $onchangefirst,'',$suffix).'<br />';
                   2275:         } elsif ($possdirs == 1) {
                   2276:             $singledir = (keys(%nonemptydirs))[0];
                   2277:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2278:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2279:             }
                   2280:             delete($selimport_menus{$singledir});
                   2281:         }
                   2282:     } elsif ($numdirs == 1) {
                   2283:         $singledir = (keys(%files))[0];
                   2284:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2285:             if ($only) {
                   2286:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2287:                 unless ($possexts{lc($ext)}) {
                   2288:                     next;
                   2289:                 }
1.1315    raeburn  2290:             } else {
                   2291:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2292:             }
                   2293:             push(@singledirfiles,$file);
                   2294:         }
                   2295:         if (@singledirfiles) {
1.1315    raeburn  2296:             $possdirs = 1;
1.1248    raeburn  2297:         }
                   2298:     }
                   2299:     if (($possdirs == 1) && (@singledirfiles)) {
                   2300:         my $showdir = $singledir;
                   2301:         if ($singledir eq '') {
                   2302:             $showdir = '/';
                   2303:         }
                   2304:         $output = $lt{'dire'}.
                   2305:                   '<select name="'.$firstselectname.'">'.
                   2306:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2307:                   '</select><br />'.
                   2308:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2309:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2310:         foreach my $file (@singledirfiles) {
                   2311:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2312:         }
                   2313:         $output .= '</select><br />'."\n";
                   2314:     }
                   2315:     return ($possdirs,$output);
                   2316: }
                   2317: 
1.565     albertel 2318: =pod
                   2319: 
1.256     matthew  2320: =head1 Excel and CSV file utility routines
                   2321: 
                   2322: =cut
                   2323: 
                   2324: ###############################################################
                   2325: ###############################################################
                   2326: 
                   2327: =pod
                   2328: 
1.1162    raeburn  2329: =over 4
                   2330: 
1.648     raeburn  2331: =item * &csv_translate($text) 
1.37      matthew  2332: 
1.185     www      2333: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2334: format.
                   2335: 
                   2336: =cut
                   2337: 
1.180     matthew  2338: ###############################################################
                   2339: ###############################################################
1.37      matthew  2340: sub csv_translate {
                   2341:     my $text = shift;
                   2342:     $text =~ s/\"/\"\"/g;
1.209     albertel 2343:     $text =~ s/\n/ /g;
1.37      matthew  2344:     return $text;
                   2345: }
1.180     matthew  2346: 
                   2347: ###############################################################
                   2348: ###############################################################
                   2349: 
                   2350: =pod
                   2351: 
1.648     raeburn  2352: =item * &define_excel_formats()
1.180     matthew  2353: 
                   2354: Define some commonly used Excel cell formats.
                   2355: 
                   2356: Currently supported formats:
                   2357: 
                   2358: =over 4
                   2359: 
                   2360: =item header
                   2361: 
                   2362: =item bold
                   2363: 
                   2364: =item h1
                   2365: 
                   2366: =item h2
                   2367: 
                   2368: =item h3
                   2369: 
1.256     matthew  2370: =item h4
                   2371: 
                   2372: =item i
                   2373: 
1.180     matthew  2374: =item date
                   2375: 
                   2376: =back
                   2377: 
                   2378: Inputs: $workbook
                   2379: 
                   2380: Returns: $format, a hash reference.
                   2381: 
1.1057    foxr     2382: 
1.180     matthew  2383: =cut
                   2384: 
                   2385: ###############################################################
                   2386: ###############################################################
                   2387: sub define_excel_formats {
                   2388:     my ($workbook) = @_;
                   2389:     my $format;
                   2390:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2391:                                                 bottom    => 1,
                   2392:                                                 align     => 'center');
                   2393:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2394:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2395:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2396:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2397:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2398:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2399:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2400:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2401:     return $format;
                   2402: }
                   2403: 
                   2404: ###############################################################
                   2405: ###############################################################
1.113     bowersj2 2406: 
                   2407: =pod
                   2408: 
1.648     raeburn  2409: =item * &create_workbook()
1.255     matthew  2410: 
                   2411: Create an Excel worksheet.  If it fails, output message on the
                   2412: request object and return undefs.
                   2413: 
                   2414: Inputs: Apache request object
                   2415: 
                   2416: Returns (undef) on failure, 
                   2417:     Excel worksheet object, scalar with filename, and formats 
                   2418:     from &Apache::loncommon::define_excel_formats on success
                   2419: 
                   2420: =cut
                   2421: 
                   2422: ###############################################################
                   2423: ###############################################################
                   2424: sub create_workbook {
                   2425:     my ($r) = @_;
                   2426:         #
                   2427:     # Create the excel spreadsheet
                   2428:     my $filename = '/prtspool/'.
1.258     albertel 2429:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2430:         time.'_'.rand(1000000000).'.xls';
                   2431:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2432:     if (! defined($workbook)) {
                   2433:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2434:         $r->print(
                   2435:             '<p class="LC_error">'
                   2436:            .&mt('Problems occurred in creating the new Excel file.')
                   2437:            .' '.&mt('This error has been logged.')
                   2438:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2439:            .'</p>'
                   2440:         );
1.255     matthew  2441:         return (undef);
                   2442:     }
                   2443:     #
1.1014    foxr     2444:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2445:     #
                   2446:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2447:     return ($workbook,$filename,$format);
                   2448: }
                   2449: 
                   2450: ###############################################################
                   2451: ###############################################################
                   2452: 
                   2453: =pod
                   2454: 
1.648     raeburn  2455: =item * &create_text_file()
1.113     bowersj2 2456: 
1.542     raeburn  2457: Create a file to write to and eventually make available to the user.
1.256     matthew  2458: If file creation fails, outputs an error message on the request object and 
                   2459: return undefs.
1.113     bowersj2 2460: 
1.256     matthew  2461: Inputs: Apache request object, and file suffix
1.113     bowersj2 2462: 
1.256     matthew  2463: Returns (undef) on failure, 
                   2464:     Filehandle and filename on success.
1.113     bowersj2 2465: 
                   2466: =cut
                   2467: 
1.256     matthew  2468: ###############################################################
                   2469: ###############################################################
                   2470: sub create_text_file {
                   2471:     my ($r,$suffix) = @_;
                   2472:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2473:     my $fh;
                   2474:     my $filename = '/prtspool/'.
1.258     albertel 2475:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2476:         time.'_'.rand(1000000000).'.'.$suffix;
                   2477:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2478:     if (! defined($fh)) {
                   2479:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2480:         $r->print(
                   2481:             '<p class="LC_error">'
                   2482:            .&mt('Problems occurred in creating the output file.')
                   2483:            .' '.&mt('This error has been logged.')
                   2484:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2485:            .'</p>'
                   2486:         );
1.113     bowersj2 2487:     }
1.256     matthew  2488:     return ($fh,$filename)
1.113     bowersj2 2489: }
                   2490: 
                   2491: 
1.256     matthew  2492: =pod 
1.113     bowersj2 2493: 
                   2494: =back
                   2495: 
                   2496: =cut
1.37      matthew  2497: 
                   2498: ###############################################################
1.33      matthew  2499: ##        Home server <option> list generating code          ##
                   2500: ###############################################################
1.35      matthew  2501: 
1.169     www      2502: # ------------------------------------------
                   2503: 
                   2504: sub domain_select {
1.1289    raeburn  2505:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2506:     my @possdoms;
                   2507:     if (ref($incdoms) eq 'ARRAY') {
                   2508:         @possdoms = @{$incdoms};
                   2509:     } else {
                   2510:         @possdoms = &Apache::lonnet::all_domains();
                   2511:     }
                   2512: 
1.169     www      2513:     my %domains=map { 
1.514     albertel 2514: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2515:     } @possdoms;
                   2516: 
                   2517:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2518:         foreach my $dom (@{$excdoms}) {
                   2519:             delete($domains{$dom});
                   2520:         }
                   2521:     }
                   2522: 
1.169     www      2523:     if ($multiple) {
                   2524: 	$domains{''}=&mt('Any domain');
1.550     albertel 2525: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2526: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2527:     } else {
1.550     albertel 2528: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2529: 	return &select_form($name,$value,\%domains);
1.169     www      2530:     }
                   2531: }
                   2532: 
1.282     albertel 2533: #-------------------------------------------
                   2534: 
                   2535: =pod
                   2536: 
1.519     raeburn  2537: =head1 Routines for form select boxes
                   2538: 
                   2539: =over 4
                   2540: 
1.648     raeburn  2541: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2542: 
                   2543: Returns a string containing a <select> element int multiple mode
                   2544: 
                   2545: 
                   2546: Args:
                   2547:   $name - name of the <select> element
1.506     raeburn  2548:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2549:   $size - number of rows long the select element is
1.283     albertel 2550:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2551:           (shown text should already have been &mt())
1.506     raeburn  2552:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2553: 
1.282     albertel 2554: =cut
                   2555: 
                   2556: #-------------------------------------------
1.169     www      2557: sub multiple_select_form {
1.284     albertel 2558:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2559:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2560:     my $output='';
1.191     matthew  2561:     if (! defined($size)) {
                   2562:         $size = 4;
1.283     albertel 2563:         if (scalar(keys(%$hash))<4) {
                   2564:             $size = scalar(keys(%$hash));
1.191     matthew  2565:         }
                   2566:     }
1.734     bisitz   2567:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2568:     my @order;
1.506     raeburn  2569:     if (ref($order) eq 'ARRAY')  {
                   2570:         @order = @{$order};
                   2571:     } else {
                   2572:         @order = sort(keys(%$hash));
1.501     banghart 2573:     }
                   2574:     if (exists($$hash{'select_form_order'})) {
                   2575:         @order = @{$$hash{'select_form_order'}};
                   2576:     }
                   2577:         
1.284     albertel 2578:     foreach my $key (@order) {
1.356     albertel 2579:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2580:         $output.='selected="selected" ' if ($selected{$key});
                   2581:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2582:     }
                   2583:     $output.="</select>\n";
                   2584:     return $output;
                   2585: }
                   2586: 
1.88      www      2587: #-------------------------------------------
                   2588: 
                   2589: =pod
                   2590: 
1.1254    raeburn  2591: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2592: 
                   2593: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2594: allow a user to select options from a ref to a hash containing:
                   2595: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2596: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2597: An optional arg -- $readonly -- if true will cause the select form
                   2598: to be disabled, e.g., for the case where an instructor has a section-
                   2599: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2600: 
1.88      www      2601: See lonrights.pm for an example invocation and use.
                   2602: 
                   2603: =cut
                   2604: 
                   2605: #-------------------------------------------
                   2606: sub select_form {
1.1228    raeburn  2607:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2608:     return unless (ref($hashref) eq 'HASH');
                   2609:     if ($onchange) {
                   2610:         $onchange = ' onchange="'.$onchange.'"';
                   2611:     }
1.1228    raeburn  2612:     my $disabled;
                   2613:     if ($readonly) {
                   2614:         $disabled = ' disabled="disabled"';
                   2615:     }
                   2616:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2617:     my @keys;
1.970     raeburn  2618:     if (exists($hashref->{'select_form_order'})) {
                   2619: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2620:     } else {
1.970     raeburn  2621: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2622:     }
1.356     albertel 2623:     foreach my $key (@keys) {
                   2624:         $selectform.=
                   2625: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2626:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2627:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2628:     }
                   2629:     $selectform.="</select>";
                   2630:     return $selectform;
                   2631: }
                   2632: 
1.475     www      2633: # For display filters
                   2634: 
                   2635: sub display_filter {
1.1074    raeburn  2636:     my ($context) = @_;
1.475     www      2637:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2638:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2639:     my $phraseinput = 'hidden';
                   2640:     my $includeinput = 'hidden';
                   2641:     my ($checked,$includetypestext);
                   2642:     if ($env{'form.displayfilter'} eq 'containing') {
                   2643:         $phraseinput = 'text'; 
                   2644:         if ($context eq 'parmslog') {
                   2645:             $includeinput = 'checkbox';
                   2646:             if ($env{'form.includetypes'}) {
                   2647:                 $checked = ' checked="checked"';
                   2648:             }
                   2649:             $includetypestext = &mt('Include parameter types');
                   2650:         }
                   2651:     } else {
                   2652:         $includetypestext = '&nbsp;';
                   2653:     }
                   2654:     my ($additional,$secondid,$thirdid);
                   2655:     if ($context eq 'parmslog') {
                   2656:         $additional = 
                   2657:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2658:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2659:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2660:             '</label>';
                   2661:         $secondid = 'includetypes';
                   2662:         $thirdid = 'includetypestext';
                   2663:     }
                   2664:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2665:                                                     '$secondid','$thirdid')";
                   2666:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2667: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2668: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2669: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2670:            &mt('Filter: [_1]',
1.477     www      2671: 	   &select_form($env{'form.displayfilter'},
                   2672: 			'displayfilter',
1.970     raeburn  2673: 			{'currentfolder' => 'Current folder/page',
1.477     www      2674: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2675: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2676: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2677:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2678:                          '" />'.$additional;
                   2679: }
                   2680: 
                   2681: sub display_filter_js {
                   2682:     my $includetext = &mt('Include parameter types');
                   2683:     return <<"ENDJS";
                   2684:   
                   2685: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2686:     var firstType = 'hidden';
                   2687:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2688:         firstType = 'text';
                   2689:     }
                   2690:     firstObject = document.getElementById(firstid);
                   2691:     if (typeof(firstObject) == 'object') {
                   2692:         if (firstObject.type != firstType) {
                   2693:             changeInputType(firstObject,firstType);
                   2694:         }
                   2695:     }
                   2696:     if (context == 'parmslog') {
                   2697:         var secondType = 'hidden';
                   2698:         if (firstType == 'text') {
                   2699:             secondType = 'checkbox';
                   2700:         }
                   2701:         secondObject = document.getElementById(secondid);  
                   2702:         if (typeof(secondObject) == 'object') {
                   2703:             if (secondObject.type != secondType) {
                   2704:                 changeInputType(secondObject,secondType);
                   2705:             }
                   2706:         }
                   2707:         var textItem = document.getElementById(thirdid);
                   2708:         var currtext = textItem.innerHTML;
                   2709:         var newtext;
                   2710:         if (firstType == 'text') {
                   2711:             newtext = '$includetext';
                   2712:         } else {
                   2713:             newtext = '&nbsp;';
                   2714:         }
                   2715:         if (currtext != newtext) {
                   2716:             textItem.innerHTML = newtext;
                   2717:         }
                   2718:     }
                   2719:     return;
                   2720: }
                   2721: 
                   2722: function changeInputType(oldObject,newType) {
                   2723:     var newObject = document.createElement('input');
                   2724:     newObject.type = newType;
                   2725:     if (oldObject.size) {
                   2726:         newObject.size = oldObject.size;
                   2727:     }
                   2728:     if (oldObject.value) {
                   2729:         newObject.value = oldObject.value;
                   2730:     }
                   2731:     if (oldObject.name) {
                   2732:         newObject.name = oldObject.name;
                   2733:     }
                   2734:     if (oldObject.id) {
                   2735:         newObject.id = oldObject.id;
                   2736:     }
                   2737:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2738:     return;
                   2739: }
                   2740: 
                   2741: ENDJS
1.475     www      2742: }
                   2743: 
1.167     www      2744: sub gradeleveldescription {
                   2745:     my $gradelevel=shift;
                   2746:     my %gradelevels=(0 => 'Not specified',
                   2747: 		     1 => 'Grade 1',
                   2748: 		     2 => 'Grade 2',
                   2749: 		     3 => 'Grade 3',
                   2750: 		     4 => 'Grade 4',
                   2751: 		     5 => 'Grade 5',
                   2752: 		     6 => 'Grade 6',
                   2753: 		     7 => 'Grade 7',
                   2754: 		     8 => 'Grade 8',
                   2755: 		     9 => 'Grade 9',
                   2756: 		     10 => 'Grade 10',
                   2757: 		     11 => 'Grade 11',
                   2758: 		     12 => 'Grade 12',
                   2759: 		     13 => 'Grade 13',
                   2760: 		     14 => '100 Level',
                   2761: 		     15 => '200 Level',
                   2762: 		     16 => '300 Level',
                   2763: 		     17 => '400 Level',
                   2764: 		     18 => 'Graduate Level');
                   2765:     return &mt($gradelevels{$gradelevel});
                   2766: }
                   2767: 
1.163     www      2768: sub select_level_form {
                   2769:     my ($deflevel,$name)=@_;
                   2770:     unless ($deflevel) { $deflevel=0; }
1.167     www      2771:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2772:     for (my $i=0; $i<=18; $i++) {
                   2773:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2774:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2775:                 ">".&gradeleveldescription($i)."</option>\n";
                   2776:     }
                   2777:     $selectform.="</select>";
                   2778:     return $selectform;
1.163     www      2779: }
1.167     www      2780: 
1.35      matthew  2781: #-------------------------------------------
                   2782: 
1.45      matthew  2783: =pod
                   2784: 
1.1256    raeburn  2785: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2786: 
                   2787: Returns a string containing a <select name='$name' size='1'> form to 
                   2788: allow a user to select the domain to preform an operation in.  
                   2789: See loncreateuser.pm for an example invocation and use.
                   2790: 
1.90      www      2791: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2792: selected");
                   2793: 
1.743     raeburn  2794: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2795: 
1.910     raeburn  2796: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2797: 
1.1121    raeburn  2798: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2799: 
                   2800: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2801: 
1.1256    raeburn  2802: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2803: 
1.35      matthew  2804: =cut
                   2805: 
                   2806: #-------------------------------------------
1.34      matthew  2807: sub select_dom_form {
1.1256    raeburn  2808:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2809:     if ($onchange) {
1.874     raeburn  2810:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2811:     }
1.1256    raeburn  2812:     if ($disabled) {
                   2813:         $disabled = ' disabled="disabled"';
                   2814:     }
1.1121    raeburn  2815:     my (@domains,%exclude);
1.910     raeburn  2816:     if (ref($incdoms) eq 'ARRAY') {
                   2817:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2818:     } else {
                   2819:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2820:     }
1.90      www      2821:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2822:     if (ref($excdoms) eq 'ARRAY') {
                   2823:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2824:     }
1.1256    raeburn  2825:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2826:     foreach my $dom (@domains) {
1.1121    raeburn  2827:         next if ($exclude{$dom});
1.356     albertel 2828:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2829:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2830:         if ($showdomdesc) {
                   2831:             if ($dom ne '') {
                   2832:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2833:                 if ($domdesc ne '') {
                   2834:                     $selectdomain .= ' ('.$domdesc.')';
                   2835:                 }
                   2836:             } 
                   2837:         }
                   2838:         $selectdomain .= "</option>\n";
1.34      matthew  2839:     }
                   2840:     $selectdomain.="</select>";
                   2841:     return $selectdomain;
                   2842: }
                   2843: 
1.35      matthew  2844: #-------------------------------------------
                   2845: 
1.45      matthew  2846: =pod
                   2847: 
1.648     raeburn  2848: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2849: 
1.586     raeburn  2850: input: 4 arguments (two required, two optional) - 
                   2851:     $domain - domain of new user
                   2852:     $name - name of form element
                   2853:     $default - Value of 'default' causes a default item to be first 
                   2854:                             option, and selected by default. 
                   2855:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2856:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2857: output: returns 2 items: 
1.586     raeburn  2858: (a) form element which contains either:
                   2859:    (i) <select name="$name">
                   2860:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2861:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2862:        </select>
                   2863:        form item if there are multiple library servers in $domain, or
                   2864:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2865:        if there is only one library server in $domain.
                   2866: 
                   2867: (b) number of library servers found.
                   2868: 
                   2869: See loncreateuser.pm for example of use.
1.35      matthew  2870: 
                   2871: =cut
                   2872: 
                   2873: #-------------------------------------------
1.586     raeburn  2874: sub home_server_form_item {
                   2875:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2876:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2877:     my $result;
                   2878:     my $numlib = keys(%servers);
                   2879:     if ($numlib > 1) {
                   2880:         $result .= '<select name="'.$name.'" />'."\n";
                   2881:         if ($default) {
1.804     bisitz   2882:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2883:                        '</option>'."\n";
                   2884:         }
                   2885:         foreach my $hostid (sort(keys(%servers))) {
                   2886:             $result.= '<option value="'.$hostid.'">'.
                   2887: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2888:         }
                   2889:         $result .= '</select>'."\n";
                   2890:     } elsif ($numlib == 1) {
                   2891:         my $hostid;
                   2892:         foreach my $item (keys(%servers)) {
                   2893:             $hostid = $item;
                   2894:         }
                   2895:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2896:                    $hostid.'" />';
                   2897:                    if (!$hide) {
                   2898:                        $result .= $hostid.' '.$servers{$hostid};
                   2899:                    }
                   2900:                    $result .= "\n";
                   2901:     } elsif ($default) {
                   2902:         $result .= '<input type="hidden" name="'.$name.
                   2903:                    '" value="default" />';
                   2904:                    if (!$hide) {
                   2905:                        $result .= &mt('default');
                   2906:                    }
                   2907:                    $result .= "\n";
1.33      matthew  2908:     }
1.586     raeburn  2909:     return ($result,$numlib);
1.33      matthew  2910: }
1.112     bowersj2 2911: 
                   2912: =pod
                   2913: 
1.534     albertel 2914: =back 
                   2915: 
1.112     bowersj2 2916: =cut
1.87      matthew  2917: 
                   2918: ###############################################################
1.112     bowersj2 2919: ##                  Decoding User Agent                      ##
1.87      matthew  2920: ###############################################################
                   2921: 
                   2922: =pod
                   2923: 
1.112     bowersj2 2924: =head1 Decoding the User Agent
                   2925: 
                   2926: =over 4
                   2927: 
                   2928: =item * &decode_user_agent()
1.87      matthew  2929: 
                   2930: Inputs: $r
                   2931: 
                   2932: Outputs:
                   2933: 
                   2934: =over 4
                   2935: 
1.112     bowersj2 2936: =item * $httpbrowser
1.87      matthew  2937: 
1.112     bowersj2 2938: =item * $clientbrowser
1.87      matthew  2939: 
1.112     bowersj2 2940: =item * $clientversion
1.87      matthew  2941: 
1.112     bowersj2 2942: =item * $clientmathml
1.87      matthew  2943: 
1.112     bowersj2 2944: =item * $clientunicode
1.87      matthew  2945: 
1.112     bowersj2 2946: =item * $clientos
1.87      matthew  2947: 
1.1137    raeburn  2948: =item * $clientmobile
                   2949: 
1.1141    raeburn  2950: =item * $clientinfo
                   2951: 
1.1194    raeburn  2952: =item * $clientosversion
                   2953: 
1.87      matthew  2954: =back
                   2955: 
1.157     matthew  2956: =back 
                   2957: 
1.87      matthew  2958: =cut
                   2959: 
                   2960: ###############################################################
                   2961: ###############################################################
                   2962: sub decode_user_agent {
1.247     albertel 2963:     my ($r)=@_;
1.87      matthew  2964:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2965:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2966:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2967:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2968:     my $clientbrowser='unknown';
                   2969:     my $clientversion='0';
                   2970:     my $clientmathml='';
                   2971:     my $clientunicode='0';
1.1137    raeburn  2972:     my $clientmobile=0;
1.1194    raeburn  2973:     my $clientosversion='';
1.87      matthew  2974:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2975:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2976: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2977: 	    $clientbrowser=$bname;
                   2978:             $httpbrowser=~/$vreg/i;
                   2979: 	    $clientversion=$1;
                   2980:             $clientmathml=($clientversion>=$minv);
                   2981:             $clientunicode=($clientversion>=$univ);
                   2982: 	}
                   2983:     }
                   2984:     my $clientos='unknown';
1.1141    raeburn  2985:     my $clientinfo;
1.87      matthew  2986:     if (($httpbrowser=~/linux/i) ||
                   2987:         ($httpbrowser=~/unix/i) ||
                   2988:         ($httpbrowser=~/ux/i) ||
                   2989:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2990:     if (($httpbrowser=~/vax/i) ||
                   2991:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2992:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2993:     if (($httpbrowser=~/mac/i) ||
                   2994:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2995:     if ($httpbrowser=~/win/i) {
                   2996:         $clientos='win';
                   2997:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2998:             $clientosversion = $1;
                   2999:         }
                   3000:     }
1.87      matthew  3001:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3002:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3003:         $clientmobile=lc($1);
                   3004:     }
1.1141    raeburn  3005:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3006:         $clientinfo = 'firefox-'.$1;
                   3007:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3008:         $clientinfo = 'chromeframe-'.$1;
                   3009:     }
1.87      matthew  3010:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3011:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3012:             $clientosversion);
1.87      matthew  3013: }
                   3014: 
1.32      matthew  3015: ###############################################################
                   3016: ##    Authentication changing form generation subroutines    ##
                   3017: ###############################################################
                   3018: ##
                   3019: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3020: ## hash, and have reasonable default values.
                   3021: ##
                   3022: ##    formname = the name given in the <form> tag.
1.35      matthew  3023: #-------------------------------------------
                   3024: 
1.45      matthew  3025: =pod
                   3026: 
1.112     bowersj2 3027: =head1 Authentication Routines
                   3028: 
                   3029: =over 4
                   3030: 
1.648     raeburn  3031: =item * &authform_xxxxxx()
1.35      matthew  3032: 
                   3033: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3034: handle some of the conveniences required for authentication forms.  
                   3035: This is not an optimal method, but it works.  
                   3036: 
                   3037: =over 4
                   3038: 
1.112     bowersj2 3039: =item * authform_header
1.35      matthew  3040: 
1.112     bowersj2 3041: =item * authform_authorwarning
1.35      matthew  3042: 
1.112     bowersj2 3043: =item * authform_nochange
1.35      matthew  3044: 
1.112     bowersj2 3045: =item * authform_kerberos
1.35      matthew  3046: 
1.112     bowersj2 3047: =item * authform_internal
1.35      matthew  3048: 
1.112     bowersj2 3049: =item * authform_filesystem
1.35      matthew  3050: 
1.1310    raeburn  3051: =item * authform_lti
                   3052: 
1.35      matthew  3053: =back
                   3054: 
1.648     raeburn  3055: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3056: 
1.35      matthew  3057: =cut
                   3058: 
                   3059: #-------------------------------------------
1.32      matthew  3060: sub authform_header{  
                   3061:     my %in = (
                   3062:         formname => 'cu',
1.80      albertel 3063:         kerb_def_dom => '',
1.32      matthew  3064:         @_,
                   3065:     );
                   3066:     $in{'formname'} = 'document.' . $in{'formname'};
                   3067:     my $result='';
1.80      albertel 3068: 
                   3069: #---------------------------------------------- Code for upper case translation
                   3070:     my $Javascript_toUpperCase;
                   3071:     unless ($in{kerb_def_dom}) {
                   3072:         $Javascript_toUpperCase =<<"END";
                   3073:         switch (choice) {
                   3074:            case 'krb': currentform.elements[choicearg].value =
                   3075:                currentform.elements[choicearg].value.toUpperCase();
                   3076:                break;
                   3077:            default:
                   3078:         }
                   3079: END
                   3080:     } else {
                   3081:         $Javascript_toUpperCase = "";
                   3082:     }
                   3083: 
1.165     raeburn  3084:     my $radioval = "'nochange'";
1.591     raeburn  3085:     if (defined($in{'curr_authtype'})) {
                   3086:         if ($in{'curr_authtype'} ne '') {
                   3087:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3088:         }
1.174     matthew  3089:     }
1.165     raeburn  3090:     my $argfield = 'null';
1.591     raeburn  3091:     if (defined($in{'mode'})) {
1.165     raeburn  3092:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3093:             if (defined($in{'curr_autharg'})) {
                   3094:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3095:                     $argfield = "'$in{'curr_autharg'}'";
                   3096:                 }
                   3097:             }
                   3098:         }
                   3099:     }
                   3100: 
1.32      matthew  3101:     $result.=<<"END";
                   3102: var current = new Object();
1.165     raeburn  3103: current.radiovalue = $radioval;
                   3104: current.argfield = $argfield;
1.32      matthew  3105: 
                   3106: function changed_radio(choice,currentform) {
                   3107:     var choicearg = choice + 'arg';
                   3108:     // If a radio button in changed, we need to change the argfield
                   3109:     if (current.radiovalue != choice) {
                   3110:         current.radiovalue = choice;
                   3111:         if (current.argfield != null) {
                   3112:             currentform.elements[current.argfield].value = '';
                   3113:         }
                   3114:         if (choice == 'nochange') {
                   3115:             current.argfield = null;
                   3116:         } else {
                   3117:             current.argfield = choicearg;
                   3118:             switch(choice) {
                   3119:                 case 'krb': 
                   3120:                     currentform.elements[current.argfield].value = 
                   3121:                         "$in{'kerb_def_dom'}";
                   3122:                 break;
                   3123:               default:
                   3124:                 break;
                   3125:             }
                   3126:         }
                   3127:     }
                   3128:     return;
                   3129: }
1.22      www      3130: 
1.32      matthew  3131: function changed_text(choice,currentform) {
                   3132:     var choicearg = choice + 'arg';
                   3133:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3134:         $Javascript_toUpperCase
1.32      matthew  3135:         // clear old field
                   3136:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3137:             currentform.elements[current.argfield].value = '';
                   3138:         }
                   3139:         current.argfield = choicearg;
                   3140:     }
                   3141:     set_auth_radio_buttons(choice,currentform);
                   3142:     return;
1.20      www      3143: }
1.32      matthew  3144: 
                   3145: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3146:     var numauthchoices = currentform.login.length;
                   3147:     if (typeof numauthchoices  == "undefined") {
                   3148:         return;
                   3149:     } 
1.32      matthew  3150:     var i=0;
1.986     raeburn  3151:     while (i < numauthchoices) {
1.32      matthew  3152:         if (currentform.login[i].value == newvalue) { break; }
                   3153:         i++;
                   3154:     }
1.986     raeburn  3155:     if (i == numauthchoices) {
1.32      matthew  3156:         return;
                   3157:     }
                   3158:     current.radiovalue = newvalue;
                   3159:     currentform.login[i].checked = true;
                   3160:     return;
                   3161: }
                   3162: END
                   3163:     return $result;
                   3164: }
                   3165: 
1.1106    raeburn  3166: sub authform_authorwarning {
1.32      matthew  3167:     my $result='';
1.144     matthew  3168:     $result='<i>'.
                   3169:         &mt('As a general rule, only authors or co-authors should be '.
                   3170:             'filesystem authenticated '.
                   3171:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3172:     return $result;
                   3173: }
                   3174: 
1.1106    raeburn  3175: sub authform_nochange {
1.32      matthew  3176:     my %in = (
                   3177:               formname => 'document.cu',
                   3178:               kerb_def_dom => 'MSU.EDU',
                   3179:               @_,
                   3180:           );
1.1106    raeburn  3181:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3182:     my $result;
1.1104    raeburn  3183:     if (!$authnum) {
1.1105    raeburn  3184:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3185:     } else {
                   3186:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3187:                   '<input type="radio" name="login" value="nochange" '.
                   3188:                   'checked="checked" onclick="'.
1.281     albertel 3189:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3190: 	    '</label>';
1.586     raeburn  3191:     }
1.32      matthew  3192:     return $result;
                   3193: }
                   3194: 
1.591     raeburn  3195: sub authform_kerberos {
1.32      matthew  3196:     my %in = (
                   3197:               formname => 'document.cu',
                   3198:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3199:               kerb_def_auth => 'krb4',
1.32      matthew  3200:               @_,
                   3201:               );
1.586     raeburn  3202:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3203:         $autharg,$jscall,$disabled);
1.1106    raeburn  3204:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3205:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3206:        $check5 = ' checked="checked"';
1.80      albertel 3207:     } else {
1.772     bisitz   3208:        $check4 = ' checked="checked"';
1.80      albertel 3209:     }
1.1259    raeburn  3210:     if ($in{'readonly'}) {
                   3211:         $disabled = ' disabled="disabled"';
                   3212:     }
1.165     raeburn  3213:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3214:     if (defined($in{'curr_authtype'})) {
                   3215:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3216:             $krbcheck = ' checked="checked"';
1.623     raeburn  3217:             if (defined($in{'mode'})) {
                   3218:                 if ($in{'mode'} eq 'modifyuser') {
                   3219:                     $krbcheck = '';
                   3220:                 }
                   3221:             }
1.591     raeburn  3222:             if (defined($in{'curr_kerb_ver'})) {
                   3223:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3224:                     $check5 = ' checked="checked"';
1.591     raeburn  3225:                     $check4 = '';
                   3226:                 } else {
1.772     bisitz   3227:                     $check4 = ' checked="checked"';
1.591     raeburn  3228:                     $check5 = '';
                   3229:                 }
1.586     raeburn  3230:             }
1.591     raeburn  3231:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3232:                 $krbarg = $in{'curr_autharg'};
                   3233:             }
1.586     raeburn  3234:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3235:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3236:                     $result = 
                   3237:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3238:         $in{'curr_autharg'},$krbver);
                   3239:                 } else {
                   3240:                     $result =
                   3241:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3242:                 }
                   3243:                 return $result; 
                   3244:             }
                   3245:         }
                   3246:     } else {
                   3247:         if ($authnum == 1) {
1.784     bisitz   3248:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3249:         }
                   3250:     }
1.586     raeburn  3251:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3252:         return;
1.587     raeburn  3253:     } elsif ($authtype eq '') {
1.591     raeburn  3254:         if (defined($in{'mode'})) {
1.587     raeburn  3255:             if ($in{'mode'} eq 'modifycourse') {
                   3256:                 if ($authnum == 1) {
1.1259    raeburn  3257:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3258:                 }
                   3259:             }
                   3260:         }
1.586     raeburn  3261:     }
                   3262:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3263:     if ($authtype eq '') {
                   3264:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3265:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3266:                     $krbcheck.$disabled.' />';
1.586     raeburn  3267:     }
                   3268:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3269:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3270:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3271:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3272:          $in{'curr_authtype'} eq 'krb4')) {
                   3273:         $result .= &mt
1.144     matthew  3274:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3275:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3276:          '<label>'.$authtype,
1.281     albertel 3277:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3278:              'value="'.$krbarg.'" '.
1.1259    raeburn  3279:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3280:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3281:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3282: 	 '</label>');
1.586     raeburn  3283:     } elsif ($can_assign{'krb4'}) {
                   3284:         $result .= &mt
                   3285:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3286:          '[_3] Version 4 [_4]',
                   3287:          '<label>'.$authtype,
                   3288:          '</label><input type="text" size="10" name="krbarg" '.
                   3289:              'value="'.$krbarg.'" '.
1.1259    raeburn  3290:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3291:          '<label><input type="hidden" name="krbver" value="4" />',
                   3292:          '</label>');
                   3293:     } elsif ($can_assign{'krb5'}) {
                   3294:         $result .= &mt
                   3295:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3296:          '[_3] Version 5 [_4]',
                   3297:          '<label>'.$authtype,
                   3298:          '</label><input type="text" size="10" name="krbarg" '.
                   3299:              'value="'.$krbarg.'" '.
1.1259    raeburn  3300:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3301:          '<label><input type="hidden" name="krbver" value="5" />',
                   3302:          '</label>');
                   3303:     }
1.32      matthew  3304:     return $result;
                   3305: }
                   3306: 
1.1106    raeburn  3307: sub authform_internal {
1.586     raeburn  3308:     my %in = (
1.32      matthew  3309:                 formname => 'document.cu',
                   3310:                 kerb_def_dom => 'MSU.EDU',
                   3311:                 @_,
                   3312:                 );
1.1259    raeburn  3313:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3314:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3315:     if ($in{'readonly'}) {
                   3316:         $disabled = ' disabled="disabled"';
                   3317:     }
1.591     raeburn  3318:     if (defined($in{'curr_authtype'})) {
                   3319:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3320:             if ($can_assign{'int'}) {
1.772     bisitz   3321:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3322:                 if (defined($in{'mode'})) {
                   3323:                     if ($in{'mode'} eq 'modifyuser') {
                   3324:                         $intcheck = '';
                   3325:                     }
                   3326:                 }
1.591     raeburn  3327:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3328:                     $intarg = $in{'curr_autharg'};
                   3329:                 }
                   3330:             } else {
                   3331:                 $result = &mt('Currently internally authenticated.');
                   3332:                 return $result;
1.165     raeburn  3333:             }
                   3334:         }
1.586     raeburn  3335:     } else {
                   3336:         if ($authnum == 1) {
1.784     bisitz   3337:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3338:         }
                   3339:     }
                   3340:     if (!$can_assign{'int'}) {
                   3341:         return;
1.587     raeburn  3342:     } elsif ($authtype eq '') {
1.591     raeburn  3343:         if (defined($in{'mode'})) {
1.587     raeburn  3344:             if ($in{'mode'} eq 'modifycourse') {
                   3345:                 if ($authnum == 1) {
1.1259    raeburn  3346:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3347:                 }
                   3348:             }
                   3349:         }
1.165     raeburn  3350:     }
1.586     raeburn  3351:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3352:     if ($authtype eq '') {
                   3353:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3354:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3355:     }
1.605     bisitz   3356:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3357:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3358:     $result = &mt
1.144     matthew  3359:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3360:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3361:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3362:     return $result;
                   3363: }
                   3364: 
1.1104    raeburn  3365: sub authform_local {
1.32      matthew  3366:     my %in = (
                   3367:               formname => 'document.cu',
                   3368:               kerb_def_dom => 'MSU.EDU',
                   3369:               @_,
                   3370:               );
1.1259    raeburn  3371:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3372:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3373:     if ($in{'readonly'}) {
                   3374:         $disabled = ' disabled="disabled"';
                   3375:     } 
1.591     raeburn  3376:     if (defined($in{'curr_authtype'})) {
                   3377:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3378:             if ($can_assign{'loc'}) {
1.772     bisitz   3379:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3380:                 if (defined($in{'mode'})) {
                   3381:                     if ($in{'mode'} eq 'modifyuser') {
                   3382:                         $loccheck = '';
                   3383:                     }
                   3384:                 }
1.591     raeburn  3385:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3386:                     $locarg = $in{'curr_autharg'};
                   3387:                 }
                   3388:             } else {
                   3389:                 $result = &mt('Currently using local (institutional) authentication.');
                   3390:                 return $result;
1.165     raeburn  3391:             }
                   3392:         }
1.586     raeburn  3393:     } else {
                   3394:         if ($authnum == 1) {
1.784     bisitz   3395:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3396:         }
                   3397:     }
                   3398:     if (!$can_assign{'loc'}) {
                   3399:         return;
1.587     raeburn  3400:     } elsif ($authtype eq '') {
1.591     raeburn  3401:         if (defined($in{'mode'})) {
1.587     raeburn  3402:             if ($in{'mode'} eq 'modifycourse') {
                   3403:                 if ($authnum == 1) {
1.1259    raeburn  3404:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3405:                 }
                   3406:             }
                   3407:         }
1.165     raeburn  3408:     }
1.586     raeburn  3409:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3410:     if ($authtype eq '') {
                   3411:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3412:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3413:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3414:     }
                   3415:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3416:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3417:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3418:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3419:     return $result;
                   3420: }
                   3421: 
1.1106    raeburn  3422: sub authform_filesystem {
1.32      matthew  3423:     my %in = (
                   3424:               formname => 'document.cu',
                   3425:               kerb_def_dom => 'MSU.EDU',
                   3426:               @_,
                   3427:               );
1.1259    raeburn  3428:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3429:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3430:     if ($in{'readonly'}) {
                   3431:         $disabled = ' disabled="disabled"';
                   3432:     }
1.591     raeburn  3433:     if (defined($in{'curr_authtype'})) {
                   3434:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3435:             if ($can_assign{'fsys'}) {
1.772     bisitz   3436:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3437:                 if (defined($in{'mode'})) {
                   3438:                     if ($in{'mode'} eq 'modifyuser') {
                   3439:                         $fsyscheck = '';
                   3440:                     }
                   3441:                 }
1.586     raeburn  3442:             } else {
                   3443:                 $result = &mt('Currently Filesystem Authenticated.');
                   3444:                 return $result;
1.1259    raeburn  3445:             }
1.586     raeburn  3446:         }
                   3447:     } else {
                   3448:         if ($authnum == 1) {
1.784     bisitz   3449:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3450:         }
                   3451:     }
                   3452:     if (!$can_assign{'fsys'}) {
                   3453:         return;
1.587     raeburn  3454:     } elsif ($authtype eq '') {
1.591     raeburn  3455:         if (defined($in{'mode'})) {
1.587     raeburn  3456:             if ($in{'mode'} eq 'modifycourse') {
                   3457:                 if ($authnum == 1) {
1.1259    raeburn  3458:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3459:                 }
                   3460:             }
                   3461:         }
1.586     raeburn  3462:     }
                   3463:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3464:     if ($authtype eq '') {
                   3465:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3466:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3467:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3468:     }
1.1310    raeburn  3469:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3470:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3471:     $result = &mt
1.144     matthew  3472:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3473:          '<label>'.$authtype,'</label>'.$autharg);
                   3474:     return $result;
                   3475: }
                   3476: 
                   3477: sub authform_lti {
                   3478:     my %in = (
                   3479:               formname => 'document.cu',
                   3480:               kerb_def_dom => 'MSU.EDU',
                   3481:               @_,
                   3482:               );
                   3483:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3484:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3485:     if ($in{'readonly'}) {
                   3486:         $disabled = ' disabled="disabled"';
                   3487:     }
                   3488:     if (defined($in{'curr_authtype'})) {
                   3489:         if ($in{'curr_authtype'} eq 'lti') {
                   3490:             if ($can_assign{'lti'}) {
                   3491:                 $lticheck = 'checked="checked" ';
                   3492:                 if (defined($in{'mode'})) {
                   3493:                     if ($in{'mode'} eq 'modifyuser') {
                   3494:                         $lticheck = '';
                   3495:                     }
                   3496:                 }
                   3497:             } else {
                   3498:                 $result = &mt('Currently LTI Authenticated.');
                   3499:                 return $result;
                   3500:             }
                   3501:         }
                   3502:     } else {
                   3503:         if ($authnum == 1) {
                   3504:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3505:         }
                   3506:     }
                   3507:     if (!$can_assign{'lti'}) {
                   3508:         return;
                   3509:     } elsif ($authtype eq '') {
                   3510:         if (defined($in{'mode'})) {
                   3511:             if ($in{'mode'} eq 'modifycourse') {
                   3512:                 if ($authnum == 1) {
                   3513:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3514:                 }
                   3515:             }
                   3516:         }
                   3517:     }
                   3518:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3519:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3520:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3521:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3522:                     $jscall.'"'.$disabled.' />';
                   3523:     }
                   3524:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3525:     if ($authtype) {
                   3526:         $result = &mt('[_1] LTI Authenticated',
                   3527:                       '<label>'.$authtype.'</label>'.$autharg);
                   3528:     } else {
                   3529:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3530:                   $autharg;
                   3531:     }
1.32      matthew  3532:     return $result;
                   3533: }
                   3534: 
1.586     raeburn  3535: sub get_assignable_auth {
                   3536:     my ($dom) = @_;
                   3537:     if ($dom eq '') {
                   3538:         $dom = $env{'request.role.domain'};
                   3539:     }
                   3540:     my %can_assign = (
                   3541:                           krb4 => 1,
                   3542:                           krb5 => 1,
                   3543:                           int  => 1,
                   3544:                           loc  => 1,
1.1310    raeburn  3545:                           lti  => 1,
1.586     raeburn  3546:                      );
                   3547:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3548:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3549:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3550:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3551:             my $context;
                   3552:             if ($env{'request.role'} =~ /^au/) {
                   3553:                 $context = 'author';
1.1259    raeburn  3554:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3555:                 $context = 'domain';
                   3556:             } elsif ($env{'request.course.id'}) {
                   3557:                 $context = 'course';
                   3558:             }
                   3559:             if ($context) {
                   3560:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3561:                    %can_assign = %{$authhash->{$context}}; 
                   3562:                 }
                   3563:             }
                   3564:         }
                   3565:     }
                   3566:     my $authnum = 0;
                   3567:     foreach my $key (keys(%can_assign)) {
                   3568:         if ($can_assign{$key}) {
                   3569:             $authnum ++;
                   3570:         }
                   3571:     }
                   3572:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3573:         $authnum --;
                   3574:     }
                   3575:     return ($authnum,%can_assign);
                   3576: }
                   3577: 
1.1331    raeburn  3578: sub check_passwd_rules {
                   3579:     my ($domain,$plainpass) = @_;
                   3580:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3581:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3582:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3583:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3584:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3585:             if ($passwdconf{'min'} > $min) {
                   3586:                 $min = $passwdconf{'min'};
                   3587:             }
1.1331    raeburn  3588:         }
                   3589:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3590:             $max = $passwdconf{'max'};
                   3591:         }
                   3592:         @chars = @{$passwdconf{'chars'}};
                   3593:     }
                   3594:     if (($min) && (length($plainpass) < $min)) {
                   3595:         push(@brokerule,'min');
                   3596:     }
                   3597:     if (($max) && (length($plainpass) > $max)) {
                   3598:         push(@brokerule,'max');
                   3599:     }
                   3600:     if (@chars) {
                   3601:         my %rules;
                   3602:         map { $rules{$_} = 1; } @chars;
                   3603:         if ($rules{'uc'}) {
                   3604:             unless ($plainpass =~ /[A-Z]/) {
                   3605:                 push(@brokerule,'uc');
                   3606:             }
                   3607:         }
                   3608:         if ($rules{'lc'}) {
1.1332    raeburn  3609:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3610:                 push(@brokerule,'lc');
                   3611:             }
                   3612:         }
                   3613:         if ($rules{'num'}) {
                   3614:             unless ($plainpass =~ /\d/) {
                   3615:                 push(@brokerule,'num');
                   3616:             }
                   3617:         }
                   3618:         if ($rules{'spec'}) {
                   3619:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3620:                 push(@brokerule,'spec');
                   3621:             }
                   3622:         }
                   3623:     }
                   3624:     if (@brokerule) {
                   3625:         my %rulenames = &Apache::lonlocal::texthash(
                   3626:             uc   => 'At least one upper case letter',
                   3627:             lc   => 'At least one lower case letter',
                   3628:             num  => 'At least one number',
                   3629:             spec => 'At least one non-alphanumeric',
                   3630:         );
                   3631:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3632:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3633:         $rulenames{'num'} .= ': 0123456789';
                   3634:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3635:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3636:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3637:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3638:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3639:             if (grep(/^$rule$/,@brokerule)) {
                   3640:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3641:             }
                   3642:         }
                   3643:         $warning .= '</ul>';
                   3644:     }
1.1332    raeburn  3645:     if (wantarray) {
                   3646:         return @brokerule;
                   3647:     }
1.1331    raeburn  3648:     return $warning;
                   3649: }
                   3650: 
1.1376    raeburn  3651: sub passwd_validation_js {
1.1377  ! raeburn  3652:     my ($currpasswdval,$domain,$context,$id) = @_;
        !          3653:     my (%passwdconf,$alertmsg);
        !          3654:     if ($context eq 'linkprot') {
        !          3655:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
        !          3656:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
        !          3657:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
        !          3658:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
        !          3659:             }
        !          3660:         }
        !          3661:         if ($id eq 'add') {
        !          3662:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
        !          3663:         } elsif ($id =~ /^\d+$/) {
        !          3664:             my $pos = $id+1;
        !          3665:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
        !          3666:         } else {
        !          3667:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
        !          3668:         }
        !          3669:     } else {
        !          3670:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
        !          3671:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
        !          3672:     }
1.1376    raeburn  3673:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3674:     $numrules = 0;
                   3675:     $min = $Apache::lonnet::passwdmin;
                   3676:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3677:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3678:             if ($passwdconf{'min'} > $min) {
                   3679:                 $min = $passwdconf{'min'};
                   3680:             }
                   3681:         }
                   3682:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3683:             $max = $passwdconf{'max'};
                   3684:             $numrules ++;
                   3685:         }
                   3686:         @chars = @{$passwdconf{'chars'}};
                   3687:         if (@chars) {
                   3688:             $numrules ++;
                   3689:         }
                   3690:     }
                   3691:     if ($min > 0) {
                   3692:         $numrules ++;
                   3693:     }
                   3694:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3695:         if ($min) {
                   3696:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3697:         }
                   3698:         if ($max) {
                   3699:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3700:         }
                   3701:         my (@charalerts,@charrules);
                   3702:         if (@chars) {
                   3703:             if (grep(/^uc$/,@chars)) {
                   3704:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3705:                 push(@charrules,'uc');
                   3706:             }
                   3707:             if (grep(/^lc$/,@chars)) {
                   3708:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3709:                 push(@charrules,'lc');
                   3710:             }
                   3711:             if (grep(/^num$/,@chars)) {
                   3712:                 push(@charalerts,&mt('contain at least one number'));
                   3713:                 push(@charrules,'num');
                   3714:             }
                   3715:             if (grep(/^spec$/,@chars)) {
                   3716:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3717:                 push(@charrules,'spec');
                   3718:             }
                   3719:         }
                   3720:         $intargjs = qq|            var rulesmsg = '';\n|.
                   3721:                     qq|            var currpwval = $currpasswdval;\n|;
                   3722:             if ($min) {
                   3723:                 $intargjs .= qq|
                   3724:             if (currpwval.length < $min) {
                   3725:                 rulesmsg += ' - $alert{min}';
                   3726:             }
                   3727: |;
                   3728:             }
                   3729:             if ($max) {
                   3730:                 $intargjs .= qq|
                   3731:             if (currpwval.length > $max) {
                   3732:                 rulesmsg += ' - $alert{max}';
                   3733:             }
                   3734: |;
                   3735:             }
                   3736:             if (@chars > 0) {
                   3737:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3738:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3739:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3740:                              qq|            var charrules = new Array($charrulestr);\n|.
                   3741:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3742:                 my %rules;
                   3743:                 map { $rules{$_} = 1; } @chars;
                   3744:                 if ($rules{'uc'}) {
                   3745:                     $intargjs .= qq|
                   3746:             var ucRegExp = /[A-Z]/;
                   3747:             if (!ucRegExp.test(currpwval)) {
                   3748:                 brokerules.push('uc');
                   3749:             }
                   3750: |;
                   3751:                 }
                   3752:                 if ($rules{'lc'}) {
                   3753:                     $intargjs .= qq|
                   3754:             var lcRegExp = /[a-z]/;
                   3755:             if (!lcRegExp.test(currpwval)) {
                   3756:                 brokerules.push('lc');
                   3757:             }
                   3758: |;
                   3759:                 }
                   3760:                 if ($rules{'num'}) {
                   3761:                      $intargjs .= qq|
                   3762:             var numRegExp = /[0-9]/;
                   3763:             if (!numRegExp.test(currpwval)) {
                   3764:                 brokerules.push('num');
                   3765:             }
                   3766: |;
                   3767:                 }
                   3768:                 if ($rules{'spec'}) {
                   3769:                      $intargjs .= q|
                   3770:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3771:             if (!specRegExp.test(currpwval)) {
                   3772:                 brokerules.push('spec');
                   3773:             }
                   3774: |;
                   3775:                 }
                   3776:                 $intargjs .= qq|
                   3777:             if (brokerules.length > 0) {
                   3778:                 for (var i=0; i<brokerules.length; i++) {
                   3779:                     for (var j=0; j<charrules.length; j++) {
                   3780:                         if (brokerules[i] == charrules[j]) {
                   3781:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3782:                             break;
                   3783:                         }
                   3784:                     }
                   3785:                 }
                   3786:             }
                   3787: |;
                   3788:             }
                   3789:             $intargjs .= qq|
                   3790:             if (rulesmsg != '') {
                   3791:                 rulesmsg = '$alertmsg'+rulesmsg;
                   3792:                 alert(rulesmsg);
                   3793:                 return false;
                   3794:             }
                   3795: |;
                   3796:     }
                   3797:     return ($numrules,$intargjs);
                   3798: }
                   3799: 
1.80      albertel 3800: ###############################################################
                   3801: ##    Get Kerberos Defaults for Domain                 ##
                   3802: ###############################################################
                   3803: ##
                   3804: ## Returns default kerberos version and an associated argument
                   3805: ## as listed in file domain.tab. If not listed, provides
                   3806: ## appropriate default domain and kerberos version.
                   3807: ##
                   3808: #-------------------------------------------
                   3809: 
                   3810: =pod
                   3811: 
1.648     raeburn  3812: =item * &get_kerberos_defaults()
1.80      albertel 3813: 
                   3814: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3815: version and domain. If not found, it defaults to version 4 and the 
                   3816: domain of the server.
1.80      albertel 3817: 
1.648     raeburn  3818: =over 4
                   3819: 
1.80      albertel 3820: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3821: 
1.648     raeburn  3822: =back
                   3823: 
                   3824: =back
                   3825: 
1.80      albertel 3826: =cut
                   3827: 
                   3828: #-------------------------------------------
                   3829: sub get_kerberos_defaults {
                   3830:     my $domain=shift;
1.641     raeburn  3831:     my ($krbdef,$krbdefdom);
                   3832:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3833:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3834:         $krbdef = $domdefaults{'auth_def'};
                   3835:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3836:     } else {
1.80      albertel 3837:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3838:         my $krbdefdom=$1;
                   3839:         $krbdefdom=~tr/a-z/A-Z/;
                   3840:         $krbdef = "krb4";
                   3841:     }
                   3842:     return ($krbdef,$krbdefdom);
                   3843: }
1.112     bowersj2 3844: 
1.32      matthew  3845: 
1.46      matthew  3846: ###############################################################
                   3847: ##                Thesaurus Functions                        ##
                   3848: ###############################################################
1.20      www      3849: 
1.46      matthew  3850: =pod
1.20      www      3851: 
1.112     bowersj2 3852: =head1 Thesaurus Functions
                   3853: 
                   3854: =over 4
                   3855: 
1.648     raeburn  3856: =item * &initialize_keywords()
1.46      matthew  3857: 
                   3858: Initializes the package variable %Keywords if it is empty.  Uses the
                   3859: package variable $thesaurus_db_file.
                   3860: 
                   3861: =cut
                   3862: 
                   3863: ###################################################
                   3864: 
                   3865: sub initialize_keywords {
                   3866:     return 1 if (scalar keys(%Keywords));
                   3867:     # If we are here, %Keywords is empty, so fill it up
                   3868:     #   Make sure the file we need exists...
                   3869:     if (! -e $thesaurus_db_file) {
                   3870:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3871:                                  " failed because it does not exist");
                   3872:         return 0;
                   3873:     }
                   3874:     #   Set up the hash as a database
                   3875:     my %thesaurus_db;
                   3876:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3877:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3878:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3879:                                  $thesaurus_db_file);
                   3880:         return 0;
                   3881:     } 
                   3882:     #  Get the average number of appearances of a word.
                   3883:     my $avecount = $thesaurus_db{'average.count'};
                   3884:     #  Put keywords (those that appear > average) into %Keywords
                   3885:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3886:         my ($count,undef) = split /:/,$data;
                   3887:         $Keywords{$word}++ if ($count > $avecount);
                   3888:     }
                   3889:     untie %thesaurus_db;
                   3890:     # Remove special values from %Keywords.
1.356     albertel 3891:     foreach my $value ('total.count','average.count') {
                   3892:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3893:   }
1.46      matthew  3894:     return 1;
                   3895: }
                   3896: 
                   3897: ###################################################
                   3898: 
                   3899: =pod
                   3900: 
1.648     raeburn  3901: =item * &keyword($word)
1.46      matthew  3902: 
                   3903: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3904: than the average number of times in the thesaurus database.  Calls 
                   3905: &initialize_keywords
                   3906: 
                   3907: =cut
                   3908: 
                   3909: ###################################################
1.20      www      3910: 
                   3911: sub keyword {
1.46      matthew  3912:     return if (!&initialize_keywords());
                   3913:     my $word=lc(shift());
                   3914:     $word=~s/\W//g;
                   3915:     return exists($Keywords{$word});
1.20      www      3916: }
1.46      matthew  3917: 
                   3918: ###############################################################
                   3919: 
                   3920: =pod 
1.20      www      3921: 
1.648     raeburn  3922: =item * &get_related_words()
1.46      matthew  3923: 
1.160     matthew  3924: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3925: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3926: will be returned.  The order of the words returned is determined by the
                   3927: database which holds them.
                   3928: 
                   3929: Uses global $thesaurus_db_file.
                   3930: 
1.1057    foxr     3931: 
1.46      matthew  3932: =cut
                   3933: 
                   3934: ###############################################################
                   3935: sub get_related_words {
                   3936:     my $keyword = shift;
                   3937:     my %thesaurus_db;
                   3938:     if (! -e $thesaurus_db_file) {
                   3939:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3940:                                  "failed because the file does not exist");
                   3941:         return ();
                   3942:     }
                   3943:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3944:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3945:         return ();
                   3946:     } 
                   3947:     my @Words=();
1.429     www      3948:     my $count=0;
1.46      matthew  3949:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3950: 	# The first element is the number of times
                   3951: 	# the word appears.  We do not need it now.
1.429     www      3952: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3953: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3954: 	my $threshold=$mostfrequentcount/10;
                   3955:         foreach my $possibleword (@RelatedWords) {
                   3956:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3957:             if ($wordcount>$threshold) {
                   3958: 		push(@Words,$word);
                   3959:                 $count++;
                   3960:                 if ($count>10) { last; }
                   3961: 	    }
1.20      www      3962:         }
                   3963:     }
1.46      matthew  3964:     untie %thesaurus_db;
                   3965:     return @Words;
1.14      harris41 3966: }
1.1090    foxr     3967: ###############################################################
                   3968: #
                   3969: #  Spell checking
                   3970: #
                   3971: 
                   3972: =pod
                   3973: 
1.1142    raeburn  3974: =back
                   3975: 
1.1090    foxr     3976: =head1 Spell checking
                   3977: 
                   3978: =over 4
                   3979: 
                   3980: =item * &check_spelling($wordlist $language)
                   3981: 
                   3982: Takes a string containing words and feeds it to an external
                   3983: spellcheck program via a pipeline. Returns a string containing
                   3984: them mis-spelled words.
                   3985: 
                   3986: Parameters:
                   3987: 
                   3988: =over 4
                   3989: 
                   3990: =item - $wordlist
                   3991: 
                   3992: String that will be fed into the spellcheck program.
                   3993: 
                   3994: =item - $language
                   3995: 
                   3996: Language string that specifies the language for which the spell
                   3997: check will be performed.
                   3998: 
                   3999: =back
                   4000: 
                   4001: =back
                   4002: 
                   4003: Note: This sub assumes that aspell is installed.
                   4004: 
                   4005: 
                   4006: =cut
                   4007: 
1.46      matthew  4008: 
1.1090    foxr     4009: sub check_spelling {
                   4010:     my ($wordlist, $language) = @_;
1.1091    foxr     4011:     my @misspellings;
                   4012:     
                   4013:     # Generate the speller and set the langauge.
                   4014:     # if explicitly selected:
1.1090    foxr     4015: 
1.1091    foxr     4016:     my $speller = Text::Aspell->new;
1.1090    foxr     4017:     if ($language) {
1.1091    foxr     4018: 	$speller->set_option('lang', $language);
1.1090    foxr     4019:     }
                   4020: 
1.1091    foxr     4021:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4022: 
1.1091    foxr     4023:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4024: 
1.1091    foxr     4025:     foreach my $word (@words) {
                   4026: 	if(! $speller->check($word)) {
                   4027: 	    push(@misspellings, $word);
1.1090    foxr     4028: 	}
                   4029:     }
1.1091    foxr     4030:     return join(' ', @misspellings);
                   4031:     
1.1090    foxr     4032: }
                   4033: 
1.61      www      4034: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4035: =pod
                   4036: 
1.112     bowersj2 4037: =head1 User Name Functions
                   4038: 
                   4039: =over 4
                   4040: 
1.648     raeburn  4041: =item * &plainname($uname,$udom,$first)
1.81      albertel 4042: 
1.112     bowersj2 4043: Takes a users logon name and returns it as a string in
1.226     albertel 4044: "first middle last generation" form 
                   4045: if $first is set to 'lastname' then it returns it as
                   4046: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4047: 
                   4048: =cut
1.61      www      4049: 
1.295     www      4050: 
1.81      albertel 4051: ###############################################################
1.61      www      4052: sub plainname {
1.226     albertel 4053:     my ($uname,$udom,$first)=@_;
1.537     albertel 4054:     return if (!defined($uname) || !defined($udom));
1.295     www      4055:     my %names=&getnames($uname,$udom);
1.226     albertel 4056:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4057: 					  $names{'middlename'},
                   4058: 					  $names{'lastname'},
                   4059: 					  $names{'generation'},$first);
                   4060:     $name=~s/^\s+//;
1.62      www      4061:     $name=~s/\s+$//;
                   4062:     $name=~s/\s+/ /g;
1.353     albertel 4063:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4064:     return $name;
1.61      www      4065: }
1.66      www      4066: 
                   4067: # -------------------------------------------------------------------- Nickname
1.81      albertel 4068: =pod
                   4069: 
1.648     raeburn  4070: =item * &nickname($uname,$udom)
1.81      albertel 4071: 
                   4072: Gets a users name and returns it as a string as
                   4073: 
                   4074: "&quot;nickname&quot;"
1.66      www      4075: 
1.81      albertel 4076: if the user has a nickname or
                   4077: 
                   4078: "first middle last generation"
                   4079: 
                   4080: if the user does not
                   4081: 
                   4082: =cut
1.66      www      4083: 
                   4084: sub nickname {
                   4085:     my ($uname,$udom)=@_;
1.537     albertel 4086:     return if (!defined($uname) || !defined($udom));
1.295     www      4087:     my %names=&getnames($uname,$udom);
1.68      albertel 4088:     my $name=$names{'nickname'};
1.66      www      4089:     if ($name) {
                   4090:        $name='&quot;'.$name.'&quot;'; 
                   4091:     } else {
                   4092:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4093: 	     $names{'lastname'}.' '.$names{'generation'};
                   4094:        $name=~s/\s+$//;
                   4095:        $name=~s/\s+/ /g;
                   4096:     }
                   4097:     return $name;
                   4098: }
                   4099: 
1.295     www      4100: sub getnames {
                   4101:     my ($uname,$udom)=@_;
1.537     albertel 4102:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4103:     if ($udom eq 'public' && $uname eq 'public') {
                   4104: 	return ('lastname' => &mt('Public'));
                   4105:     }
1.295     www      4106:     my $id=$uname.':'.$udom;
                   4107:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4108:     if ($cached) {
                   4109: 	return %{$names};
                   4110:     } else {
                   4111: 	my %loadnames=&Apache::lonnet::get('environment',
                   4112:                     ['firstname','middlename','lastname','generation','nickname'],
                   4113: 					 $udom,$uname);
                   4114: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4115: 	return %loadnames;
                   4116:     }
                   4117: }
1.61      www      4118: 
1.542     raeburn  4119: # -------------------------------------------------------------------- getemails
1.648     raeburn  4120: 
1.542     raeburn  4121: =pod
                   4122: 
1.648     raeburn  4123: =item * &getemails($uname,$udom)
1.542     raeburn  4124: 
                   4125: Gets a user's email information and returns it as a hash with keys:
                   4126: notification, critnotification, permanentemail
                   4127: 
                   4128: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4129: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4130:  
1.648     raeburn  4131: 
1.542     raeburn  4132: =cut
                   4133: 
1.648     raeburn  4134: 
1.466     albertel 4135: sub getemails {
                   4136:     my ($uname,$udom)=@_;
                   4137:     if ($udom eq 'public' && $uname eq 'public') {
                   4138: 	return;
                   4139:     }
1.467     www      4140:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4141:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4142:     my $id=$uname.':'.$udom;
                   4143:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4144:     if ($cached) {
                   4145: 	return %{$names};
                   4146:     } else {
                   4147: 	my %loadnames=&Apache::lonnet::get('environment',
                   4148:                     			   ['notification','critnotification',
                   4149: 					    'permanentemail'],
                   4150: 					   $udom,$uname);
                   4151: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4152: 	return %loadnames;
                   4153:     }
                   4154: }
                   4155: 
1.551     albertel 4156: sub flush_email_cache {
                   4157:     my ($uname,$udom)=@_;
                   4158:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4159:     if (!$uname) { $uname=$env{'user.name'};   }
                   4160:     return if ($udom eq 'public' && $uname eq 'public');
                   4161:     my $id=$uname.':'.$udom;
                   4162:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4163: }
                   4164: 
1.728     raeburn  4165: # -------------------------------------------------------------------- getlangs
                   4166: 
                   4167: =pod
                   4168: 
                   4169: =item * &getlangs($uname,$udom)
                   4170: 
                   4171: Gets a user's language preference and returns it as a hash with key:
                   4172: language.
                   4173: 
                   4174: =cut
                   4175: 
                   4176: 
                   4177: sub getlangs {
                   4178:     my ($uname,$udom) = @_;
                   4179:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4180:     if (!$uname) { $uname=$env{'user.name'};   }
                   4181:     my $id=$uname.':'.$udom;
                   4182:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4183:     if ($cached) {
                   4184:         return %{$langs};
                   4185:     } else {
                   4186:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4187:                                            $udom,$uname);
                   4188:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4189:         return %loadlangs;
                   4190:     }
                   4191: }
                   4192: 
                   4193: sub flush_langs_cache {
                   4194:     my ($uname,$udom)=@_;
                   4195:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4196:     if (!$uname) { $uname=$env{'user.name'};   }
                   4197:     return if ($udom eq 'public' && $uname eq 'public');
                   4198:     my $id=$uname.':'.$udom;
                   4199:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4200: }
                   4201: 
1.61      www      4202: # ------------------------------------------------------------------ Screenname
1.81      albertel 4203: 
                   4204: =pod
                   4205: 
1.648     raeburn  4206: =item * &screenname($uname,$udom)
1.81      albertel 4207: 
                   4208: Gets a users screenname and returns it as a string
                   4209: 
                   4210: =cut
1.61      www      4211: 
                   4212: sub screenname {
                   4213:     my ($uname,$udom)=@_;
1.258     albertel 4214:     if ($uname eq $env{'user.name'} &&
                   4215: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4216:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4217:     return $names{'screenname'};
1.62      www      4218: }
                   4219: 
1.212     albertel 4220: 
1.802     bisitz   4221: # ------------------------------------------------------------- Confirm Wrapper
                   4222: =pod
                   4223: 
1.1142    raeburn  4224: =item * &confirmwrapper($message)
1.802     bisitz   4225: 
                   4226: Wrap messages about completion of operation in box
                   4227: 
                   4228: =cut
                   4229: 
                   4230: sub confirmwrapper {
                   4231:     my ($message)=@_;
                   4232:     if ($message) {
                   4233:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4234:                .$message."\n"
                   4235:                .'</div>'."\n";
                   4236:     } else {
                   4237:         return $message;
                   4238:     }
                   4239: }
                   4240: 
1.62      www      4241: # ------------------------------------------------------------- Message Wrapper
                   4242: 
                   4243: sub messagewrapper {
1.369     www      4244:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4245:     return 
1.441     albertel 4246:         '<a href="/adm/email?compose=individual&amp;'.
                   4247:         'recname='.$username.'&amp;recdom='.$domain.
                   4248: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4249:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4250: }
1.802     bisitz   4251: 
1.74      www      4252: # --------------------------------------------------------------- Notes Wrapper
                   4253: 
                   4254: sub noteswrapper {
                   4255:     my ($link,$un,$do)=@_;
                   4256:     return 
1.896     amueller 4257: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4258: }
1.802     bisitz   4259: 
1.62      www      4260: # ------------------------------------------------------------- Aboutme Wrapper
                   4261: 
                   4262: sub aboutmewrapper {
1.1070    raeburn  4263:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4264:     if (!defined($username)  && !defined($domain)) {
                   4265:         return;
                   4266:     }
1.1096    raeburn  4267:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4268: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4269: }
                   4270: 
                   4271: # ------------------------------------------------------------ Syllabus Wrapper
                   4272: 
                   4273: sub syllabuswrapper {
1.707     bisitz   4274:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4275:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4276: }
1.14      harris41 4277: 
1.802     bisitz   4278: # -----------------------------------------------------------------------------
                   4279: 
1.208     matthew  4280: sub track_student_link {
1.887     raeburn  4281:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4282:     my $link ="/adm/trackstudent?";
1.208     matthew  4283:     my $title = 'View recent activity';
                   4284:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4285:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4286:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4287:         $title .= ' of this student';
1.268     albertel 4288:     } 
1.208     matthew  4289:     if (defined($target) && $target !~ /^\s*$/) {
                   4290:         $target = qq{target="$target"};
                   4291:     } else {
                   4292:         $target = '';
                   4293:     }
1.268     albertel 4294:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4295:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4296:     $title = &mt($title);
                   4297:     $linktext = &mt($linktext);
1.448     albertel 4298:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4299: 	&help_open_topic('View_recent_activity');
1.208     matthew  4300: }
                   4301: 
1.781     raeburn  4302: sub slot_reservations_link {
                   4303:     my ($linktext,$sname,$sdom,$target) = @_;
                   4304:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4305:     my $title = 'View slot reservation history';
                   4306:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4307:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4308:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4309:         $title .= ' of this student';
                   4310:     }
                   4311:     if (defined($target) && $target !~ /^\s*$/) {
                   4312:         $target = qq{target="$target"};
                   4313:     } else {
                   4314:         $target = '';
                   4315:     }
                   4316:     $title = &mt($title);
                   4317:     $linktext = &mt($linktext);
                   4318:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4319: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4320: 
                   4321: }
                   4322: 
1.508     www      4323: # ===================================================== Display a student photo
                   4324: 
                   4325: 
1.509     albertel 4326: sub student_image_tag {
1.508     www      4327:     my ($domain,$user)=@_;
                   4328:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4329:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4330: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4331:     } else {
                   4332: 	return '';
                   4333:     }
                   4334: }
                   4335: 
1.112     bowersj2 4336: =pod
                   4337: 
                   4338: =back
                   4339: 
                   4340: =head1 Access .tab File Data
                   4341: 
                   4342: =over 4
                   4343: 
1.648     raeburn  4344: =item * &languageids() 
1.112     bowersj2 4345: 
                   4346: returns list of all language ids
                   4347: 
                   4348: =cut
                   4349: 
1.14      harris41 4350: sub languageids {
1.16      harris41 4351:     return sort(keys(%language));
1.14      harris41 4352: }
                   4353: 
1.112     bowersj2 4354: =pod
                   4355: 
1.648     raeburn  4356: =item * &languagedescription() 
1.112     bowersj2 4357: 
                   4358: returns description of a specified language id
                   4359: 
                   4360: =cut
                   4361: 
1.14      harris41 4362: sub languagedescription {
1.125     www      4363:     my $code=shift;
                   4364:     return  ($supported_language{$code}?'* ':'').
                   4365:             $language{$code}.
1.126     www      4366: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4367: }
                   4368: 
1.1048    foxr     4369: =pod
                   4370: 
                   4371: =item * &plainlanguagedescription
                   4372: 
                   4373: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4374: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4375: 
                   4376: =cut
                   4377: 
1.145     www      4378: sub plainlanguagedescription {
                   4379:     my $code=shift;
                   4380:     return $language{$code};
                   4381: }
                   4382: 
1.1048    foxr     4383: =pod
                   4384: 
                   4385: =item * &supportedlanguagecode
                   4386: 
                   4387: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4388: code.
                   4389: 
                   4390: =cut
                   4391: 
1.145     www      4392: sub supportedlanguagecode {
                   4393:     my $code=shift;
                   4394:     return $supported_language{$code};
1.97      www      4395: }
                   4396: 
1.112     bowersj2 4397: =pod
                   4398: 
1.1048    foxr     4399: =item * &latexlanguage()
                   4400: 
                   4401: Given a language key code returns the correspondnig language to use
                   4402: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4403: is no supported hyphenation for the language code.
                   4404: 
                   4405: =cut
                   4406: 
                   4407: sub latexlanguage {
                   4408:     my $code = shift;
                   4409:     return $latex_language{$code};
                   4410: }
                   4411: 
                   4412: =pod
                   4413: 
                   4414: =item * &latexhyphenation()
                   4415: 
                   4416: Same as above but what's supplied is the language as it might be stored
                   4417: in the metadata.
                   4418: 
                   4419: =cut
                   4420: 
                   4421: sub latexhyphenation {
                   4422:     my $key = shift;
                   4423:     return $latex_language_bykey{$key};
                   4424: }
                   4425: 
                   4426: =pod
                   4427: 
1.648     raeburn  4428: =item * &copyrightids() 
1.112     bowersj2 4429: 
                   4430: returns list of all copyrights
                   4431: 
                   4432: =cut
                   4433: 
                   4434: sub copyrightids {
                   4435:     return sort(keys(%cprtag));
                   4436: }
                   4437: 
                   4438: =pod
                   4439: 
1.648     raeburn  4440: =item * &copyrightdescription() 
1.112     bowersj2 4441: 
                   4442: returns description of a specified copyright id
                   4443: 
                   4444: =cut
                   4445: 
                   4446: sub copyrightdescription {
1.166     www      4447:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4448: }
1.197     matthew  4449: 
                   4450: =pod
                   4451: 
1.648     raeburn  4452: =item * &source_copyrightids() 
1.192     taceyjo1 4453: 
                   4454: returns list of all source copyrights
                   4455: 
                   4456: =cut
                   4457: 
                   4458: sub source_copyrightids {
                   4459:     return sort(keys(%scprtag));
                   4460: }
                   4461: 
                   4462: =pod
                   4463: 
1.648     raeburn  4464: =item * &source_copyrightdescription() 
1.192     taceyjo1 4465: 
                   4466: returns description of a specified source copyright id
                   4467: 
                   4468: =cut
                   4469: 
                   4470: sub source_copyrightdescription {
                   4471:     return &mt($scprtag{shift(@_)});
                   4472: }
1.112     bowersj2 4473: 
                   4474: =pod
                   4475: 
1.648     raeburn  4476: =item * &filecategories() 
1.112     bowersj2 4477: 
                   4478: returns list of all file categories
                   4479: 
                   4480: =cut
                   4481: 
                   4482: sub filecategories {
                   4483:     return sort(keys(%category_extensions));
                   4484: }
                   4485: 
                   4486: =pod
                   4487: 
1.648     raeburn  4488: =item * &filecategorytypes() 
1.112     bowersj2 4489: 
                   4490: returns list of file types belonging to a given file
                   4491: category
                   4492: 
                   4493: =cut
                   4494: 
                   4495: sub filecategorytypes {
1.356     albertel 4496:     my ($cat) = @_;
1.1248    raeburn  4497:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4498:         return @{$category_extensions{lc($cat)}};
                   4499:     } else {
                   4500:         return ();
                   4501:     }
1.112     bowersj2 4502: }
                   4503: 
                   4504: =pod
                   4505: 
1.648     raeburn  4506: =item * &fileembstyle() 
1.112     bowersj2 4507: 
                   4508: returns embedding style for a specified file type
                   4509: 
                   4510: =cut
                   4511: 
                   4512: sub fileembstyle {
                   4513:     return $fe{lc(shift(@_))};
1.169     www      4514: }
                   4515: 
1.351     www      4516: sub filemimetype {
                   4517:     return $fm{lc(shift(@_))};
                   4518: }
                   4519: 
1.169     www      4520: 
                   4521: sub filecategoryselect {
                   4522:     my ($name,$value)=@_;
1.189     matthew  4523:     return &select_form($value,$name,
1.970     raeburn  4524:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4525: }
                   4526: 
                   4527: =pod
                   4528: 
1.648     raeburn  4529: =item * &filedescription() 
1.112     bowersj2 4530: 
                   4531: returns description for a specified file type
                   4532: 
                   4533: =cut
                   4534: 
                   4535: sub filedescription {
1.188     matthew  4536:     my $file_description = $fd{lc(shift())};
                   4537:     $file_description =~ s:([\[\]]):~$1:g;
                   4538:     return &mt($file_description);
1.112     bowersj2 4539: }
                   4540: 
                   4541: =pod
                   4542: 
1.648     raeburn  4543: =item * &filedescriptionex() 
1.112     bowersj2 4544: 
                   4545: returns description for a specified file type with
                   4546: extra formatting
                   4547: 
                   4548: =cut
                   4549: 
                   4550: sub filedescriptionex {
                   4551:     my $ex=shift;
1.188     matthew  4552:     my $file_description = $fd{lc($ex)};
                   4553:     $file_description =~ s:([\[\]]):~$1:g;
                   4554:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4555: }
                   4556: 
                   4557: # End of .tab access
                   4558: =pod
                   4559: 
                   4560: =back
                   4561: 
                   4562: =cut
                   4563: 
                   4564: # ------------------------------------------------------------------ File Types
                   4565: sub fileextensions {
                   4566:     return sort(keys(%fe));
                   4567: }
                   4568: 
1.97      www      4569: # ----------------------------------------------------------- Display Languages
                   4570: # returns a hash with all desired display languages
                   4571: #
                   4572: 
                   4573: sub display_languages {
                   4574:     my %languages=();
1.695     raeburn  4575:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4576: 	$languages{$lang}=1;
1.97      www      4577:     }
                   4578:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4579:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4580: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4581: 	    $languages{$lang}=1;
1.97      www      4582:         }
                   4583:     }
                   4584:     return %languages;
1.14      harris41 4585: }
                   4586: 
1.582     albertel 4587: sub languages {
                   4588:     my ($possible_langs) = @_;
1.695     raeburn  4589:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4590:     if (!ref($possible_langs)) {
                   4591: 	if( wantarray ) {
                   4592: 	    return @preferred_langs;
                   4593: 	} else {
                   4594: 	    return $preferred_langs[0];
                   4595: 	}
                   4596:     }
                   4597:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4598:     my @preferred_possibilities;
                   4599:     foreach my $preferred_lang (@preferred_langs) {
                   4600: 	if (exists($possibilities{$preferred_lang})) {
                   4601: 	    push(@preferred_possibilities, $preferred_lang);
                   4602: 	}
                   4603:     }
                   4604:     if( wantarray ) {
                   4605: 	return @preferred_possibilities;
                   4606:     }
                   4607:     return $preferred_possibilities[0];
                   4608: }
                   4609: 
1.742     raeburn  4610: sub user_lang {
                   4611:     my ($touname,$toudom,$fromcid) = @_;
                   4612:     my @userlangs;
                   4613:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4614:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4615:                     $env{'course.'.$fromcid.'.languages'}));
                   4616:     } else {
                   4617:         my %langhash = &getlangs($touname,$toudom);
                   4618:         if ($langhash{'languages'} ne '') {
                   4619:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4620:         } else {
                   4621:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4622:             if ($domdefs{'lang_def'} ne '') {
                   4623:                 @userlangs = ($domdefs{'lang_def'});
                   4624:             }
                   4625:         }
                   4626:     }
                   4627:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4628:     my $user_lh = Apache::localize->get_handle(@languages);
                   4629:     return $user_lh;
                   4630: }
                   4631: 
                   4632: 
1.112     bowersj2 4633: ###############################################################
                   4634: ##               Student Answer Attempts                     ##
                   4635: ###############################################################
                   4636: 
                   4637: =pod
                   4638: 
                   4639: =head1 Alternate Problem Views
                   4640: 
                   4641: =over 4
                   4642: 
1.648     raeburn  4643: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4644:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4645: 
                   4646: Return string with previous attempt on problem. Arguments:
                   4647: 
                   4648: =over 4
                   4649: 
                   4650: =item * $symb: Problem, including path
                   4651: 
                   4652: =item * $username: username of the desired student
                   4653: 
                   4654: =item * $domain: domain of the desired student
1.14      harris41 4655: 
1.112     bowersj2 4656: =item * $course: Course ID
1.14      harris41 4657: 
1.112     bowersj2 4658: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4659:     something
1.14      harris41 4660: 
1.112     bowersj2 4661: =item * $regexp: if string matches this regexp, the string will be
                   4662:     sent to $gradesub
1.14      harris41 4663: 
1.112     bowersj2 4664: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4665: 
1.1199    raeburn  4666: =item * $usec: section of the desired student
                   4667: 
                   4668: =item * $identifier: counter for student (multiple students one problem) or 
                   4669:     problem (one student; whole sequence).
                   4670: 
1.112     bowersj2 4671: =back
1.14      harris41 4672: 
1.112     bowersj2 4673: The output string is a table containing all desired attempts, if any.
1.16      harris41 4674: 
1.112     bowersj2 4675: =cut
1.1       albertel 4676: 
                   4677: sub get_previous_attempt {
1.1199    raeburn  4678:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4679:   my $prevattempts='';
1.43      ng       4680:   no strict 'refs';
1.1       albertel 4681:   if ($symb) {
1.3       albertel 4682:     my (%returnhash)=
                   4683:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4684:     if ($returnhash{'version'}) {
                   4685:       my %lasthash=();
                   4686:       my $version;
                   4687:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4688:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4689:             if ($key =~ /\.rawrndseed$/) {
                   4690:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4691:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4692:             } else {
                   4693:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4694:             }
1.19      harris41 4695:         }
1.1       albertel 4696:       }
1.596     albertel 4697:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4698:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4699:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4700:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4701:       foreach my $key (sort(keys(%lasthash))) {
                   4702: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4703: 	if ($#parts > 0) {
1.31      albertel 4704: 	  my $data=$parts[-1];
1.989     raeburn  4705:           next if ($data eq 'foilorder');
1.31      albertel 4706: 	  pop(@parts);
1.1010    www      4707:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4708:           if ($data eq 'type') {
                   4709:               unless ($showsurv) {
                   4710:                   my $id = join(',',@parts);
                   4711:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4712:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4713:                       $lasthidden{$ign.'.'.$id} = 1;
                   4714:                   }
1.945     raeburn  4715:               }
1.1199    raeburn  4716:               if ($identifier ne '') {
                   4717:                   my $id = join(',',@parts);
                   4718:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4719:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4720:                       $hidestatus{$ign.'.'.$id} = 1;
                   4721:                   }
                   4722:               }
                   4723:           } elsif ($data eq 'regrader') {
                   4724:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4725:                   my $id = join(',',@parts);
                   4726:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4727:               }
1.1010    www      4728:           } 
1.31      albertel 4729: 	} else {
1.41      ng       4730: 	  if ($#parts == 0) {
                   4731: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4732: 	  } else {
                   4733: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4734: 	  }
1.31      albertel 4735: 	}
1.16      harris41 4736:       }
1.596     albertel 4737:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4738:       if ($getattempt eq '') {
1.1199    raeburn  4739:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4740:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4741:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4742:                 foreach my $id (keys(%regraded)) {
                   4743:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4744:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4745:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4746:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4747:                     }
                   4748:                 }
                   4749:             }
1.1200    raeburn  4750:         }
                   4751: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4752:             my (@hidden,@unsolved);
1.945     raeburn  4753:             if (%typeparts) {
                   4754:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4755:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4756:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4757:                         push(@hidden,$id);
1.1199    raeburn  4758:                     } elsif ($identifier ne '') {
                   4759:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4760:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4761:                                 ($hidestatus{$id})) {
1.1200    raeburn  4762:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4763:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4764:                                 push(@{$solved{$id}},$version);
                   4765:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4766:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4767:                                 my $skip;
                   4768:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4769:                                     foreach my $reset (@{$resets{$id}}) {
                   4770:                                         if ($reset > $solved{$id}[-1]) {
                   4771:                                             $skip=1;
                   4772:                                             last;
                   4773:                                         }
                   4774:                                     }
                   4775:                                 }
                   4776:                                 unless ($skip) {
                   4777:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4778:                                     push(@unsolved,$partslist);
                   4779:                                 }
                   4780:                             }
                   4781:                         }
1.945     raeburn  4782:                     }
                   4783:                 }
                   4784:             }
                   4785:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4786:                            '<td>'.&mt('Transaction [_1]',$version);
                   4787:             if (@unsolved) {
                   4788:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4789:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4790:                                  &mt('Hide').'</label></span>';
                   4791:             }
                   4792:             $prevattempts .= '</td>';
1.945     raeburn  4793:             if (@hidden) {
                   4794:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4795:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4796:                     my $hide;
                   4797:                     foreach my $id (@hidden) {
                   4798:                         if ($key =~ /^\Q$id\E/) {
                   4799:                             $hide = 1;
                   4800:                             last;
                   4801:                         }
                   4802:                     }
                   4803:                     if ($hide) {
                   4804:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4805:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4806:                             my $value = &format_previous_attempt_value($key,
                   4807:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4808:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4809:                         } else {
                   4810:                             $prevattempts.='<td>&nbsp;</td>';
                   4811:                         }
                   4812:                     } else {
                   4813:                         if ($key =~ /\./) {
1.1212    raeburn  4814:                             my $value = $returnhash{$version.':'.$key};
                   4815:                             if ($key =~ /\.rndseed$/) {
                   4816:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4817:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4818:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4819:                                 }
                   4820:                             }
                   4821:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4822:                                            '&nbsp;</td>';
1.945     raeburn  4823:                         } else {
                   4824:                             $prevattempts.='<td>&nbsp;</td>';
                   4825:                         }
                   4826:                     }
                   4827:                 }
                   4828:             } else {
                   4829: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4830:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4831:                     my $value = $returnhash{$version.':'.$key};
                   4832:                     if ($key =~ /\.rndseed$/) {
                   4833:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4834:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4835:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4836:                         }
                   4837:                     }
                   4838:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4839:                                    '&nbsp;</td>';
1.945     raeburn  4840: 	        }
                   4841:             }
                   4842: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4843: 	 }
1.1       albertel 4844:       }
1.945     raeburn  4845:       my @currhidden = keys(%lasthidden);
1.596     albertel 4846:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4847:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4848:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4849:           if (%typeparts) {
                   4850:               my $hidden;
                   4851:               foreach my $id (@currhidden) {
                   4852:                   if ($key =~ /^\Q$id\E/) {
                   4853:                       $hidden = 1;
                   4854:                       last;
                   4855:                   }
                   4856:               }
                   4857:               if ($hidden) {
                   4858:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4859:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4860:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4861:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4862:                           $value = &$gradesub($value);
                   4863:                       }
1.1173    kruse    4864:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4865:                   } else {
                   4866:                       $prevattempts.='<td>&nbsp;</td>';
                   4867:                   }
                   4868:               } else {
                   4869:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4870:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4871:                       $value = &$gradesub($value);
                   4872:                   }
1.1173    kruse    4873:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4874:               }
                   4875:           } else {
                   4876: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4877: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4878:                   $value = &$gradesub($value);
                   4879:               }
1.1173    kruse    4880: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4881:           }
1.16      harris41 4882:       }
1.596     albertel 4883:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4884:     } else {
1.1305    raeburn  4885:       my $msg;
                   4886:       if ($symb =~ /ext\.tool$/) {
                   4887:           $msg = &mt('No grade passed back.');
                   4888:       } else {
                   4889:           $msg = &mt('Nothing submitted - no attempts.');
                   4890:       }
1.596     albertel 4891:       $prevattempts=
                   4892: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4893: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4894: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4895:     }
                   4896:   } else {
1.596     albertel 4897:     $prevattempts=
                   4898: 	  &start_data_table().&start_data_table_row().
                   4899: 	  '<td>'.&mt('No data.').'</td>'.
                   4900: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4901:   }
1.10      albertel 4902: }
                   4903: 
1.581     albertel 4904: sub format_previous_attempt_value {
                   4905:     my ($key,$value) = @_;
1.1011    www      4906:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4907:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4908:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4909:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4910:     } elsif ($key =~ /answerstring$/) {
                   4911:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4912:         my @answer = %answers;
                   4913:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4914:         my @anskeys = sort(keys(%answers));
                   4915:         if (@anskeys == 1) {
                   4916:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4917:             if ($answer =~ m{\0}) {
                   4918:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4919:             }
                   4920:             my $tag_internal_answer_name = 'INTERNAL';
                   4921:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4922:                 $value = $answer; 
                   4923:             } else {
                   4924:                 $value = $anskeys[0].'='.$answer;
                   4925:             }
                   4926:         } else {
                   4927:             foreach my $ans (@anskeys) {
                   4928:                 my $answer = $answers{$ans};
1.1001    raeburn  4929:                 if ($answer =~ m{\0}) {
                   4930:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4931:                 }
                   4932:                 $value .=  $ans.'='.$answer.'<br />';;
                   4933:             } 
                   4934:         }
1.581     albertel 4935:     } else {
1.1173    kruse    4936:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4937:     }
                   4938:     return $value;
                   4939: }
                   4940: 
                   4941: 
1.107     albertel 4942: sub relative_to_absolute {
                   4943:     my ($url,$output)=@_;
                   4944:     my $parser=HTML::TokeParser->new(\$output);
                   4945:     my $token;
                   4946:     my $thisdir=$url;
                   4947:     my @rlinks=();
                   4948:     while ($token=$parser->get_token) {
                   4949: 	if ($token->[0] eq 'S') {
                   4950: 	    if ($token->[1] eq 'a') {
                   4951: 		if ($token->[2]->{'href'}) {
                   4952: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4953: 		}
                   4954: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4955: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4956: 	    } elsif ($token->[1] eq 'base') {
                   4957: 		$thisdir=$token->[2]->{'href'};
                   4958: 	    }
                   4959: 	}
                   4960:     }
                   4961:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4962:     foreach my $link (@rlinks) {
1.726     raeburn  4963: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4964: 		($link=~/^\//) ||
                   4965: 		($link=~/^javascript:/i) ||
                   4966: 		($link=~/^mailto:/i) ||
                   4967: 		($link=~/^\#/)) {
                   4968: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4969: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4970: 	}
                   4971:     }
                   4972: # -------------------------------------------------- Deal with Applet codebases
                   4973:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4974:     return $output;
                   4975: }
                   4976: 
1.112     bowersj2 4977: =pod
                   4978: 
1.648     raeburn  4979: =item * &get_student_view()
1.112     bowersj2 4980: 
                   4981: show a snapshot of what student was looking at
                   4982: 
                   4983: =cut
                   4984: 
1.10      albertel 4985: sub get_student_view {
1.186     albertel 4986:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4987:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4988:   my (%form);
1.10      albertel 4989:   my @elements=('symb','courseid','domain','username');
                   4990:   foreach my $element (@elements) {
1.186     albertel 4991:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4992:   }
1.186     albertel 4993:   if (defined($moreenv)) {
                   4994:       %form=(%form,%{$moreenv});
                   4995:   }
1.236     albertel 4996:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4997:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4998:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4999:       $feedurl =~ s{^/adm/wrapper}{};
                   5000:   }
1.650     www      5001:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5002:   $userview=~s/\<body[^\>]*\>//gi;
                   5003:   $userview=~s/\<\/body\>//gi;
                   5004:   $userview=~s/\<html\>//gi;
                   5005:   $userview=~s/\<\/html\>//gi;
                   5006:   $userview=~s/\<head\>//gi;
                   5007:   $userview=~s/\<\/head\>//gi;
                   5008:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5009:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5010:   if (wantarray) {
                   5011:      return ($userview,$response);
                   5012:   } else {
                   5013:      return $userview;
                   5014:   }
                   5015: }
                   5016: 
                   5017: sub get_student_view_with_retries {
                   5018:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5019: 
                   5020:     my $ok = 0;                 # True if we got a good response.
                   5021:     my $content;
                   5022:     my $response;
                   5023: 
                   5024:     # Try to get the student_view done. within the retries count:
                   5025:     
                   5026:     do {
                   5027:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5028:          $ok      = $response->is_success;
                   5029:          if (!$ok) {
                   5030:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5031:          }
                   5032:          $retries--;
                   5033:     } while (!$ok && ($retries > 0));
                   5034:     
                   5035:     if (!$ok) {
                   5036:        $content = '';          # On error return an empty content.
                   5037:     }
1.651     www      5038:     if (wantarray) {
                   5039:        return ($content, $response);
                   5040:     } else {
                   5041:        return $content;
                   5042:     }
1.11      albertel 5043: }
                   5044: 
1.1349    raeburn  5045: sub css_links {
                   5046:     my ($currsymb,$level) = @_;
                   5047:     my ($links,@symbs,%cssrefs,%httpref);
                   5048:     if ($level eq 'map') {
                   5049:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5050:         if (ref($navmap)) {
                   5051:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5052:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5053:             foreach my $res (@resources) {
                   5054:                 if (ref($res) && $res->symb()) {
                   5055:                     push(@symbs,$res->symb());
                   5056:                 }
                   5057:             }
                   5058:         }
                   5059:     } else {
                   5060:         @symbs = ($currsymb);
                   5061:     }
                   5062:     foreach my $symb (@symbs) {
                   5063:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5064:         if ($css_href =~ /\S/) {
                   5065:             unless ($css_href =~ m{https?://}) {
                   5066:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5067:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5068:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5069:                 unless ($css_href =~ m{^/}) {
                   5070:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5071:                 }
                   5072:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5073:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5074:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5075:                         my $thisurl = $proburl;
                   5076:                         if ($env{'httpref.'.$proburl}) {
                   5077:                             $thisurl = $env{'httpref.'.$proburl};
                   5078:                         }
                   5079:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5080:                     }
                   5081:                 }
                   5082:             }
                   5083:             $cssrefs{$css_href} = 1;
                   5084:         }
                   5085:     }
                   5086:     if (keys(%httpref)) {
                   5087:         &Apache::lonnet::appenv(\%httpref);
                   5088:     }
                   5089:     if (keys(%cssrefs)) {
                   5090:         foreach my $css_href (keys(%cssrefs)) {
                   5091:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5092:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5093:         }
                   5094:     }
                   5095:     return $links;
                   5096: }
                   5097: 
1.112     bowersj2 5098: =pod
                   5099: 
1.648     raeburn  5100: =item * &get_student_answers() 
1.112     bowersj2 5101: 
                   5102: show a snapshot of how student was answering problem
                   5103: 
                   5104: =cut
                   5105: 
1.11      albertel 5106: sub get_student_answers {
1.100     sakharuk 5107:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5108:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5109:   my (%moreenv);
1.11      albertel 5110:   my @elements=('symb','courseid','domain','username');
                   5111:   foreach my $element (@elements) {
1.186     albertel 5112:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5113:   }
1.186     albertel 5114:   $moreenv{'grade_target'}='answer';
                   5115:   %moreenv=(%form,%moreenv);
1.497     raeburn  5116:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5117:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5118:   return $userview;
1.1       albertel 5119: }
1.116     albertel 5120: 
                   5121: =pod
                   5122: 
                   5123: =item * &submlink()
                   5124: 
1.242     albertel 5125: Inputs: $text $uname $udom $symb $target
1.116     albertel 5126: 
                   5127: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5128: 
                   5129: =cut
                   5130: 
                   5131: ###############################################
                   5132: sub submlink {
1.242     albertel 5133:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5134:     if (!($uname && $udom)) {
                   5135: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5136: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5137: 	if (!$symb) { $symb=$cursymb; }
                   5138:     }
1.254     matthew  5139:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5140:     $symb=&escape($symb);
1.960     bisitz   5141:     if ($target) { $target=" target=\"$target\""; }
                   5142:     return
                   5143:         '<a href="/adm/grades?command=submission'.
                   5144:         '&amp;symb='.$symb.
                   5145:         '&amp;student='.$uname.
                   5146:         '&amp;userdom='.$udom.'"'.
                   5147:         $target.'>'.$text.'</a>';
1.242     albertel 5148: }
                   5149: ##############################################
                   5150: 
                   5151: =pod
                   5152: 
                   5153: =item * &pgrdlink()
                   5154: 
                   5155: Inputs: $text $uname $udom $symb $target
                   5156: 
                   5157: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5158: 
                   5159: =cut
                   5160: 
                   5161: ###############################################
                   5162: sub pgrdlink {
                   5163:     my $link=&submlink(@_);
                   5164:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5165:     return $link;
                   5166: }
                   5167: ##############################################
                   5168: 
                   5169: =pod
                   5170: 
                   5171: =item * &pprmlink()
                   5172: 
                   5173: Inputs: $text $uname $udom $symb $target
                   5174: 
                   5175: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5176: student and a specific resource
1.242     albertel 5177: 
                   5178: =cut
                   5179: 
                   5180: ###############################################
                   5181: sub pprmlink {
                   5182:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5183:     if (!($uname && $udom)) {
                   5184: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5185: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5186: 	if (!$symb) { $symb=$cursymb; }
                   5187:     }
1.254     matthew  5188:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5189:     $symb=&escape($symb);
1.242     albertel 5190:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5191:     return '<a href="/adm/parmset?command=set&amp;'.
                   5192: 	'symb='.$symb.'&amp;uname='.$uname.
                   5193: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5194: }
                   5195: ##############################################
1.37      matthew  5196: 
1.112     bowersj2 5197: =pod
                   5198: 
                   5199: =back
                   5200: 
                   5201: =cut
                   5202: 
1.37      matthew  5203: ###############################################
1.51      www      5204: 
                   5205: 
                   5206: sub timehash {
1.687     raeburn  5207:     my ($thistime) = @_;
                   5208:     my $timezone = &Apache::lonlocal::gettimezone();
                   5209:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5210:                      ->set_time_zone($timezone);
                   5211:     my $wday = $dt->day_of_week();
                   5212:     if ($wday == 7) { $wday = 0; }
                   5213:     return ( 'second' => $dt->second(),
                   5214:              'minute' => $dt->minute(),
                   5215:              'hour'   => $dt->hour(),
                   5216:              'day'     => $dt->day_of_month(),
                   5217:              'month'   => $dt->month(),
                   5218:              'year'    => $dt->year(),
                   5219:              'weekday' => $wday,
                   5220:              'dayyear' => $dt->day_of_year(),
                   5221:              'dlsav'   => $dt->is_dst() );
1.51      www      5222: }
                   5223: 
1.370     www      5224: sub utc_string {
                   5225:     my ($date)=@_;
1.371     www      5226:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5227: }
                   5228: 
1.51      www      5229: sub maketime {
                   5230:     my %th=@_;
1.687     raeburn  5231:     my ($epoch_time,$timezone,$dt);
                   5232:     $timezone = &Apache::lonlocal::gettimezone();
                   5233:     eval {
                   5234:         $dt = DateTime->new( year   => $th{'year'},
                   5235:                              month  => $th{'month'},
                   5236:                              day    => $th{'day'},
                   5237:                              hour   => $th{'hour'},
                   5238:                              minute => $th{'minute'},
                   5239:                              second => $th{'second'},
                   5240:                              time_zone => $timezone,
                   5241:                          );
                   5242:     };
                   5243:     if (!$@) {
                   5244:         $epoch_time = $dt->epoch;
                   5245:         if ($epoch_time) {
                   5246:             return $epoch_time;
                   5247:         }
                   5248:     }
1.51      www      5249:     return POSIX::mktime(
                   5250:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5251:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5252: }
                   5253: 
                   5254: #########################################
1.51      www      5255: 
                   5256: sub findallcourses {
1.482     raeburn  5257:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5258:     my %roles;
                   5259:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5260:     my %courses;
1.51      www      5261:     my $now=time;
1.482     raeburn  5262:     if (!defined($uname)) {
                   5263:         $uname = $env{'user.name'};
                   5264:     }
                   5265:     if (!defined($udom)) {
                   5266:         $udom = $env{'user.domain'};
                   5267:     }
                   5268:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5269:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5270:         if (!%roles) {
                   5271:             %roles = (
                   5272:                        cc => 1,
1.907     raeburn  5273:                        co => 1,
1.482     raeburn  5274:                        in => 1,
                   5275:                        ep => 1,
                   5276:                        ta => 1,
                   5277:                        cr => 1,
                   5278:                        st => 1,
                   5279:              );
                   5280:         }
                   5281:         foreach my $entry (keys(%roleshash)) {
                   5282:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5283:             if ($trole =~ /^cr/) { 
                   5284:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5285:             } else {
                   5286:                 next if (!exists($roles{$trole}));
                   5287:             }
                   5288:             if ($tend) {
                   5289:                 next if ($tend < $now);
                   5290:             }
                   5291:             if ($tstart) {
                   5292:                 next if ($tstart > $now);
                   5293:             }
1.1058    raeburn  5294:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5295:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5296:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5297:             if ($secpart eq '') {
                   5298:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5299:                 $sec = 'none';
1.1058    raeburn  5300:                 $value .= $cnum.'/';
1.482     raeburn  5301:             } else {
                   5302:                 $cnum = $cnumpart;
                   5303:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5304:                 $value .= $cnum.'/'.$sec;
                   5305:             }
                   5306:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5307:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5308:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5309:                 }
                   5310:             } else {
                   5311:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5312:             }
1.482     raeburn  5313:         }
                   5314:     } else {
                   5315:         foreach my $key (keys(%env)) {
1.483     albertel 5316: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5317:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5318: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5319: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5320: 	        next if (%roles && !exists($roles{$role}));
                   5321: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5322:                 my $active=1;
                   5323:                 if ($starttime) {
                   5324: 		    if ($now<$starttime) { $active=0; }
                   5325:                 }
                   5326:                 if ($endtime) {
                   5327:                     if ($now>$endtime) { $active=0; }
                   5328:                 }
                   5329:                 if ($active) {
1.1058    raeburn  5330:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5331:                     if ($sec eq '') {
                   5332:                         $sec = 'none';
1.1058    raeburn  5333:                     } else {
                   5334:                         $value .= $sec;
                   5335:                     }
                   5336:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5337:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5338:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5339:                         }
                   5340:                     } else {
                   5341:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5342:                     }
1.474     raeburn  5343:                 }
                   5344:             }
1.51      www      5345:         }
                   5346:     }
1.474     raeburn  5347:     return %courses;
1.51      www      5348: }
1.37      matthew  5349: 
1.54      www      5350: ###############################################
1.474     raeburn  5351: 
                   5352: sub blockcheck {
1.1372    raeburn  5353:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5354:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5355:         my ($has_evb,$check_ipaccess);
                   5356:         my $dom = $env{'user.domain'};
                   5357:         if ($env{'request.course.id'}) {
                   5358:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5359:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5360:             my $checkrole = "cm./$cdom/$cnum";
                   5361:             my $sec = $env{'request.course.sec'};
                   5362:             if ($sec ne '') {
                   5363:                 $checkrole .= "/$sec";
                   5364:             }
                   5365:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5366:                 ($env{'request.role'} !~ /^st/)) {
                   5367:                 $has_evb = 1;
                   5368:             }
                   5369:             unless ($has_evb) {
                   5370:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5371:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5372:                     if ($udom eq $cdom) {
                   5373:                         $check_ipaccess = 1;
                   5374:                     }
                   5375:                 }
                   5376:             }
1.1375    raeburn  5377:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5378:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5379:             my $checkrole;
                   5380:             if ($env{'request.role.domain'} eq '') {
                   5381:                 $checkrole = "cm./$env{'user.domain'}/";
                   5382:             } else {
                   5383:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5384:             }
                   5385:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5386:                 $has_evb = 1;
                   5387:             }
1.1372    raeburn  5388:         }
                   5389:         unless ($has_evb || $check_ipaccess) {
                   5390:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5391:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5392:                 $dom = $udom;
                   5393:             }
                   5394:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5395:                 $check_ipaccess = 1;
                   5396:             } else {
                   5397:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5398:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5399:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5400:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5401:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5402:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5403:                         $check_ipaccess = 1;
                   5404:                     }
                   5405:                 }
                   5406:             }
                   5407:         }
                   5408:         if ($check_ipaccess) {
                   5409:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5410:             unless (defined($cached)) {
                   5411:                 my %domconfig =
                   5412:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5413:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5414:             }
                   5415:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5416:                 foreach my $id (keys(%{$ipaccessref})) {
                   5417:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5418:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5419:                         if ($range) {
                   5420:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5421:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5422:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5423:                                         return ('','','',$id,$dom);
                   5424:                                         last;
                   5425:                                     }
                   5426:                                 }
                   5427:                             }
                   5428:                         }
                   5429:                     }
                   5430:                 }
                   5431:             }
                   5432:         }
1.1373    raeburn  5433:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5434:             return ();
                   5435:         }
1.1372    raeburn  5436:     }
1.1189    raeburn  5437:     if (defined($udom) && defined($uname)) {
                   5438:         # If uname and udom are for a course, check for blocks in the course.
                   5439:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5440:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5441:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5442:             return ($startblock,$endblock,$triggerblock);
                   5443:         }
                   5444:     } else {
1.490     raeburn  5445:         $udom = $env{'user.domain'};
                   5446:         $uname = $env{'user.name'};
                   5447:     }
                   5448: 
1.502     raeburn  5449:     my $startblock = 0;
                   5450:     my $endblock = 0;
1.1062    raeburn  5451:     my $triggerblock = '';
1.1373    raeburn  5452:     my %live_courses;
                   5453:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5454:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5455:     }
1.474     raeburn  5456: 
1.490     raeburn  5457:     # If uname is for a user, and activity is course-specific, i.e.,
                   5458:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5459: 
1.490     raeburn  5460:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5461:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5462:          $activity eq 'search' || $activity eq 'reinit' ||
                   5463:          $activity eq 'alert') &&
1.1189    raeburn  5464:         ($env{'request.course.id'})) {
1.490     raeburn  5465:         foreach my $key (keys(%live_courses)) {
                   5466:             if ($key ne $env{'request.course.id'}) {
                   5467:                 delete($live_courses{$key});
                   5468:             }
                   5469:         }
                   5470:     }
                   5471: 
                   5472:     my $otheruser = 0;
                   5473:     my %own_courses;
                   5474:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5475:         # Resource belongs to user other than current user.
                   5476:         $otheruser = 1;
                   5477:         # Gather courses for current user
                   5478:         %own_courses = 
                   5479:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5480:     }
                   5481: 
                   5482:     # Gather active course roles - course coordinator, instructor, 
                   5483:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5484: 
                   5485:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5486:         my ($cdom,$cnum);
                   5487:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5488:             $cdom = $env{'course.'.$course.'.domain'};
                   5489:             $cnum = $env{'course.'.$course.'.num'};
                   5490:         } else {
1.490     raeburn  5491:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5492:         }
                   5493:         my $no_ownblock = 0;
                   5494:         my $no_userblock = 0;
1.533     raeburn  5495:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5496:             # Check if current user has 'evb' priv for this
                   5497:             if (defined($own_courses{$course})) {
                   5498:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5499:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5500:                     if ($sec ne 'none') {
                   5501:                         $checkrole .= '/'.$sec;
                   5502:                     }
                   5503:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5504:                         $no_ownblock = 1;
                   5505:                         last;
                   5506:                     }
                   5507:                 }
                   5508:             }
                   5509:             # if they have 'evb' priv and are currently not playing student
                   5510:             next if (($no_ownblock) &&
                   5511:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5512:         }
1.474     raeburn  5513:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5514:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5515:             if ($sec ne 'none') {
1.482     raeburn  5516:                 $checkrole .= '/'.$sec;
1.474     raeburn  5517:             }
1.490     raeburn  5518:             if ($otheruser) {
                   5519:                 # Resource belongs to user other than current user.
                   5520:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5521:                 my (%allroles,%userroles);
                   5522:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5523:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5524:                         my ($trole,$tdom,$tnum,$tsec);
                   5525:                         if ($entry =~ /^cr/) {
                   5526:                             ($trole,$tdom,$tnum,$tsec) = 
                   5527:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5528:                         } else {
                   5529:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5530:                         }
                   5531:                         my ($spec,$area,$trest);
                   5532:                         $area = '/'.$tdom.'/'.$tnum;
                   5533:                         $trest = $tnum;
                   5534:                         if ($tsec ne '') {
                   5535:                             $area .= '/'.$tsec;
                   5536:                             $trest .= '/'.$tsec;
                   5537:                         }
                   5538:                         $spec = $trole.'.'.$area;
                   5539:                         if ($trole =~ /^cr/) {
                   5540:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5541:                                                               $tdom,$spec,$trest,$area);
                   5542:                         } else {
                   5543:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5544:                                                                 $tdom,$spec,$trest,$area);
                   5545:                         }
                   5546:                     }
1.1276    raeburn  5547:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5548:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5549:                         if ($1) {
                   5550:                             $no_userblock = 1;
                   5551:                             last;
                   5552:                         }
1.486     raeburn  5553:                     }
                   5554:                 }
1.490     raeburn  5555:             } else {
                   5556:                 # Resource belongs to current user
                   5557:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5558:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5559:                     $no_ownblock = 1;
                   5560:                     last;
                   5561:                 }
1.474     raeburn  5562:             }
                   5563:         }
                   5564:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5565:         next if (($no_ownblock) &&
1.491     albertel 5566:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5567:         next if ($no_userblock);
1.474     raeburn  5568: 
1.1303    raeburn  5569:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5570:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5571: 
1.1062    raeburn  5572:         my ($start,$end,$trigger) = 
1.1347    raeburn  5573:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5574:         if (($start != 0) && 
                   5575:             (($startblock == 0) || ($startblock > $start))) {
                   5576:             $startblock = $start;
1.1062    raeburn  5577:             if ($trigger ne '') {
                   5578:                 $triggerblock = $trigger;
                   5579:             }
1.502     raeburn  5580:         }
                   5581:         if (($end != 0)  &&
                   5582:             (($endblock == 0) || ($endblock < $end))) {
                   5583:             $endblock = $end;
1.1062    raeburn  5584:             if ($trigger ne '') {
                   5585:                 $triggerblock = $trigger;
                   5586:             }
1.502     raeburn  5587:         }
1.490     raeburn  5588:     }
1.1062    raeburn  5589:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5590: }
                   5591: 
                   5592: sub get_blocks {
1.1347    raeburn  5593:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5594:     my $startblock = 0;
                   5595:     my $endblock = 0;
1.1062    raeburn  5596:     my $triggerblock = '';
1.490     raeburn  5597:     my $course = $cdom.'_'.$cnum;
                   5598:     $setters->{$course} = {};
                   5599:     $setters->{$course}{'staff'} = [];
                   5600:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5601:     $setters->{$course}{'triggers'} = [];
                   5602:     my (@blockers,%triggered);
                   5603:     my $now = time;
                   5604:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5605:     if ($activity eq 'docs') {
1.1348    raeburn  5606:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5607:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5608:             $blocked = 1;
                   5609:             $nosymbcache = 1;
1.1348    raeburn  5610:             $noenccheck = 1;
1.1347    raeburn  5611:         }
1.1348    raeburn  5612:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5613:         foreach my $block (@blockers) {
                   5614:             if ($block =~ /^firstaccess____(.+)$/) {
                   5615:                 my $item = $1;
                   5616:                 my $type = 'map';
                   5617:                 my $timersymb = $item;
                   5618:                 if ($item eq 'course') {
                   5619:                     $type = 'course';
                   5620:                 } elsif ($item =~ /___\d+___/) {
                   5621:                     $type = 'resource';
                   5622:                 } else {
                   5623:                     $timersymb = &Apache::lonnet::symbread($item);
                   5624:                 }
                   5625:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5626:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5627:                 $triggered{$block} = {
                   5628:                                        start => $start,
                   5629:                                        end   => $end,
                   5630:                                        type  => $type,
                   5631:                                      };
                   5632:             }
                   5633:         }
                   5634:     } else {
                   5635:         foreach my $block (keys(%commblocks)) {
                   5636:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5637:                 my ($start,$end) = ($1,$2);
                   5638:                 if ($start <= time && $end >= time) {
                   5639:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5640:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5641:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5642:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5643:                                     push(@blockers,$block);
                   5644:                                 }
                   5645:                             }
                   5646:                         }
                   5647:                     }
                   5648:                 }
                   5649:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5650:                 my $item = $1;
                   5651:                 my $timersymb = $item; 
                   5652:                 my $type = 'map';
                   5653:                 if ($item eq 'course') {
                   5654:                     $type = 'course';
                   5655:                 } elsif ($item =~ /___\d+___/) {
                   5656:                     $type = 'resource';
                   5657:                 } else {
                   5658:                     $timersymb = &Apache::lonnet::symbread($item);
                   5659:                 }
                   5660:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5661:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5662:                 if ($start && $end) {
                   5663:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5664:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5665:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5666:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5667:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5668:                                         push(@blockers,$block);
                   5669:                                         $triggered{$block} = {
                   5670:                                                                start => $start,
                   5671:                                                                end   => $end,
                   5672:                                                                type  => $type,
                   5673:                                                              };
                   5674:                                     }
                   5675:                                 }
                   5676:                             }
1.1062    raeburn  5677:                         }
                   5678:                     }
1.490     raeburn  5679:                 }
1.1062    raeburn  5680:             }
                   5681:         }
                   5682:     }
                   5683:     foreach my $blocker (@blockers) {
                   5684:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5685:             &parse_block_record($commblocks{$blocker});
                   5686:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5687:         my ($start,$end,$triggertype);
                   5688:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5689:             ($start,$end) = ($1,$2);
                   5690:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5691:             $start = $triggered{$blocker}{'start'};
                   5692:             $end = $triggered{$blocker}{'end'};
                   5693:             $triggertype = $triggered{$blocker}{'type'};
                   5694:         }
                   5695:         if ($start) {
                   5696:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5697:             if ($triggertype) {
                   5698:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5699:             } else {
                   5700:                 push(@{$$setters{$course}{'triggers'}},0);
                   5701:             }
                   5702:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5703:                 $startblock = $start;
                   5704:                 if ($triggertype) {
                   5705:                     $triggerblock = $blocker;
1.474     raeburn  5706:                 }
                   5707:             }
1.1062    raeburn  5708:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5709:                $endblock = $end;
                   5710:                if ($triggertype) {
                   5711:                    $triggerblock = $blocker;
                   5712:                }
                   5713:             }
1.474     raeburn  5714:         }
                   5715:     }
1.1062    raeburn  5716:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5717: }
                   5718: 
                   5719: sub parse_block_record {
                   5720:     my ($record) = @_;
                   5721:     my ($setuname,$setudom,$title,$blocks);
                   5722:     if (ref($record) eq 'HASH') {
                   5723:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5724:         $title = &unescape($record->{'event'});
                   5725:         $blocks = $record->{'blocks'};
                   5726:     } else {
                   5727:         my @data = split(/:/,$record,3);
                   5728:         if (scalar(@data) eq 2) {
                   5729:             $title = $data[1];
                   5730:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5731:         } else {
                   5732:             ($setuname,$setudom,$title) = @data;
                   5733:         }
                   5734:         $blocks = { 'com' => 'on' };
                   5735:     }
                   5736:     return ($setuname,$setudom,$title,$blocks);
                   5737: }
                   5738: 
1.854     kalberla 5739: sub blocking_status {
1.1372    raeburn  5740:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5741:     my %setters;
1.890     droeschl 5742: 
1.1061    raeburn  5743: # check for active blocking
1.1372    raeburn  5744:     if ($clientip eq '') {
                   5745:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5746:     }
                   5747:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5748:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5749:     my $blocked = 0;
1.1372    raeburn  5750:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5751:         $blocked = 1;
                   5752:     }
1.890     droeschl 5753: 
1.1061    raeburn  5754: # caller just wants to know whether a block is active
                   5755:     if (!wantarray) { return $blocked; }
                   5756: 
                   5757: # build a link to a popup window containing the details
                   5758:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5759: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5760:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5761:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5762:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5763:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5764:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5765:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5766:         if ($symb) {
                   5767:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5768:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5769:         }
1.1062    raeburn  5770:     }
1.1061    raeburn  5771: 
                   5772:     my $output .= <<'END_MYBLOCK';
                   5773: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5774:     var options = "width=" + w + ",height=" + h + ",";
                   5775:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5776:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5777:     var newWin = window.open(url, wdwName, options);
                   5778:     newWin.focus();
                   5779: }
1.890     droeschl 5780: END_MYBLOCK
1.854     kalberla 5781: 
1.1061    raeburn  5782:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5783:   
1.1061    raeburn  5784:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5785:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5786:     my $class = 'LC_comblock';
1.1062    raeburn  5787:     if ($activity eq 'docs') {
                   5788:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5789:         $class = '';
1.1063    raeburn  5790:     } elsif ($activity eq 'printout') {
                   5791:         $text = &mt('Printing Blocked');
1.1232    raeburn  5792:     } elsif ($activity eq 'passwd') {
                   5793:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5794:     } elsif ($activity eq 'grades') {
                   5795:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5796:     } elsif ($activity eq 'search') {
                   5797:         $text = &mt('Search Blocked');
1.1282    raeburn  5798:     } elsif ($activity eq 'alert') {
                   5799:         $text = &mt('Checking Critical Messages Blocked');
                   5800:     } elsif ($activity eq 'reinit') {
                   5801:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5802:     } elsif ($activity eq 'about') {
                   5803:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  5804:     } elsif ($activity eq 'wishlist') {
                   5805:         $text = &mt('Access to Stored Links Blocked');
                   5806:     } elsif ($activity eq 'annotate') {
                   5807:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5808:     }
1.1061    raeburn  5809:     $output .= <<"END_BLOCK";
1.1217    raeburn  5810: <div class='$class'>
1.869     kalberla 5811:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5812:   title='$text'>
                   5813:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5814:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5815:   title='$text'>$text</a>
1.867     kalberla 5816: </div>
                   5817: 
                   5818: END_BLOCK
1.474     raeburn  5819: 
1.1061    raeburn  5820:     return ($blocked, $output);
1.854     kalberla 5821: }
1.490     raeburn  5822: 
1.60      matthew  5823: ###############################################
                   5824: 
1.682     raeburn  5825: sub check_ip_acc {
1.1201    raeburn  5826:     my ($acc,$clientip)=@_;
1.682     raeburn  5827:     &Apache::lonxml::debug("acc is $acc");
                   5828:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5829:         return 1;
                   5830:     }
1.1339    raeburn  5831:     my ($ip,$allowed);
                   5832:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5833:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5834:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5835:     } else {
1.1350    raeburn  5836:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5837:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5838:     }
1.682     raeburn  5839: 
                   5840:     my $name;
1.1219    raeburn  5841:     my %access = (
                   5842:                      allowfrom => 1,
                   5843:                      denyfrom  => 0,
                   5844:                  );
                   5845:     my @allows;
                   5846:     my @denies;
                   5847:     foreach my $item (split(',',$acc)) {
                   5848:         $item =~ s/^\s*//;
                   5849:         $item =~ s/\s*$//;
                   5850:         my $pattern;
                   5851:         if ($item =~ /^\!(.+)$/) {
                   5852:             push(@denies,$1);
                   5853:         } else {
                   5854:             push(@allows,$item);
                   5855:         }
                   5856:    }
                   5857:    my $numdenies = scalar(@denies);
                   5858:    my $numallows = scalar(@allows);
                   5859:    my $count = 0;
                   5860:    foreach my $pattern (@denies,@allows) {
                   5861:         $count ++; 
                   5862:         my $acctype = 'allowfrom';
                   5863:         if ($count <= $numdenies) {
                   5864:             $acctype = 'denyfrom';
                   5865:         }
1.682     raeburn  5866:         if ($pattern =~ /\*$/) {
                   5867:             #35.8.*
                   5868:             $pattern=~s/\*//;
1.1219    raeburn  5869:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5870:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5871:             #35.8.3.[34-56]
                   5872:             my $low=$2;
                   5873:             my $high=$3;
                   5874:             $pattern=$1;
                   5875:             if ($ip =~ /^\Q$pattern\E/) {
                   5876:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5877:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5878:             }
                   5879:         } elsif ($pattern =~ /^\*/) {
                   5880:             #*.msu.edu
                   5881:             $pattern=~s/\*//;
                   5882:             if (!defined($name)) {
                   5883:                 use Socket;
                   5884:                 my $netaddr=inet_aton($ip);
                   5885:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5886:             }
1.1219    raeburn  5887:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5888:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5889:             #127.0.0.1
1.1219    raeburn  5890:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5891:         } else {
                   5892:             #some.name.com
                   5893:             if (!defined($name)) {
                   5894:                 use Socket;
                   5895:                 my $netaddr=inet_aton($ip);
                   5896:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5897:             }
1.1219    raeburn  5898:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5899:         }
                   5900:         if ($allowed =~ /^(0|1)$/) { last; }
                   5901:     }
                   5902:     if ($allowed eq '') {
                   5903:         if ($numdenies && !$numallows) {
                   5904:             $allowed = 1;
                   5905:         } else {
                   5906:             $allowed = 0;
1.682     raeburn  5907:         }
                   5908:     }
                   5909:     return $allowed;
                   5910: }
                   5911: 
                   5912: ###############################################
                   5913: 
1.60      matthew  5914: =pod
                   5915: 
1.112     bowersj2 5916: =head1 Domain Template Functions
                   5917: 
                   5918: =over 4
                   5919: 
                   5920: =item * &determinedomain()
1.60      matthew  5921: 
                   5922: Inputs: $domain (usually will be undef)
                   5923: 
1.63      www      5924: Returns: Determines which domain should be used for designs
1.60      matthew  5925: 
                   5926: =cut
1.54      www      5927: 
1.60      matthew  5928: ###############################################
1.63      www      5929: sub determinedomain {
                   5930:     my $domain=shift;
1.531     albertel 5931:     if (! $domain) {
1.60      matthew  5932:         # Determine domain if we have not been given one
1.893     raeburn  5933:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5934:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5935:         if ($env{'request.role.domain'}) { 
                   5936:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5937:         }
                   5938:     }
1.63      www      5939:     return $domain;
                   5940: }
                   5941: ###############################################
1.517     raeburn  5942: 
1.518     albertel 5943: sub devalidate_domconfig_cache {
                   5944:     my ($udom)=@_;
                   5945:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5946: }
                   5947: 
                   5948: # ---------------------- Get domain configuration for a domain
                   5949: sub get_domainconf {
                   5950:     my ($udom) = @_;
                   5951:     my $cachetime=1800;
                   5952:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5953:     if (defined($cached)) { return %{$result}; }
                   5954: 
                   5955:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5956: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5957:     my (%designhash,%legacy);
1.518     albertel 5958:     if (keys(%domconfig) > 0) {
                   5959:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5960:             if (keys(%{$domconfig{'login'}})) {
                   5961:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5962:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5963:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5964:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5965:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5966:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5967:                                         if ($key eq 'loginvia') {
                   5968:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5969:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5970:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5971:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5972: 
                   5973:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5974:                                                 } else {
                   5975:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5976:                                                 }
1.948     raeburn  5977:                                             }
1.1208    raeburn  5978:                                         } elsif ($key eq 'headtag') {
                   5979:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5980:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5981:                                             }
1.946     raeburn  5982:                                         }
1.1208    raeburn  5983:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5984:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5985:                                         }
1.946     raeburn  5986:                                     }
                   5987:                                 }
                   5988:                             }
1.1366    raeburn  5989:                         } elsif ($key eq 'saml') {
                   5990:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5991:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5992:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5993:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
                   5994:                                         foreach my $item ('text','img','alt','url','title','notsso') {
                   5995:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5996:                                         }
                   5997:                                     }
                   5998:                                 }
                   5999:                             }
1.946     raeburn  6000:                         } else {
                   6001:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6002:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6003:                                     $domconfig{'login'}{$key}{$img};
                   6004:                             }
1.699     raeburn  6005:                         }
                   6006:                     } else {
                   6007:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6008:                     }
1.632     raeburn  6009:                 }
                   6010:             } else {
                   6011:                 $legacy{'login'} = 1;
1.518     albertel 6012:             }
1.632     raeburn  6013:         } else {
                   6014:             $legacy{'login'} = 1;
1.518     albertel 6015:         }
                   6016:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6017:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6018:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6019:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6020:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6021:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6022:                         }
1.518     albertel 6023:                     }
                   6024:                 }
1.632     raeburn  6025:             } else {
                   6026:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6027:             }
1.632     raeburn  6028:         } else {
                   6029:             $legacy{'rolecolors'} = 1;
1.518     albertel 6030:         }
1.948     raeburn  6031:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6032:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6033:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6034:             }
                   6035:         }
1.632     raeburn  6036:         if (keys(%legacy) > 0) {
                   6037:             my %legacyhash = &get_legacy_domconf($udom);
                   6038:             foreach my $item (keys(%legacyhash)) {
                   6039:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6040:                     if ($legacy{'login'}) { 
                   6041:                         $designhash{$item} = $legacyhash{$item};
                   6042:                     }
                   6043:                 } else {
                   6044:                     if ($legacy{'rolecolors'}) {
                   6045:                         $designhash{$item} = $legacyhash{$item};
                   6046:                     }
1.518     albertel 6047:                 }
                   6048:             }
                   6049:         }
1.632     raeburn  6050:     } else {
                   6051:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6052:     }
                   6053:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6054: 				  $cachetime);
                   6055:     return %designhash;
                   6056: }
                   6057: 
1.632     raeburn  6058: sub get_legacy_domconf {
                   6059:     my ($udom) = @_;
                   6060:     my %legacyhash;
                   6061:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6062:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6063:     if (-e $designfile) {
1.1317    raeburn  6064:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6065:             while (my $line = <$fh>) {
                   6066:                 next if ($line =~ /^\#/);
                   6067:                 chomp($line);
                   6068:                 my ($key,$val)=(split(/\=/,$line));
                   6069:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6070:             }
                   6071:             close($fh);
                   6072:         }
                   6073:     }
1.1026    raeburn  6074:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6075:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6076:     }
                   6077:     return %legacyhash;
                   6078: }
                   6079: 
1.63      www      6080: =pod
                   6081: 
1.112     bowersj2 6082: =item * &domainlogo()
1.63      www      6083: 
                   6084: Inputs: $domain (usually will be undef)
                   6085: 
                   6086: Returns: A link to a domain logo, if the domain logo exists.
                   6087: If the domain logo does not exist, a description of the domain.
                   6088: 
                   6089: =cut
1.112     bowersj2 6090: 
1.63      www      6091: ###############################################
                   6092: sub domainlogo {
1.517     raeburn  6093:     my $domain = &determinedomain(shift);
1.518     albertel 6094:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6095:     # See if there is a logo
                   6096:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6097:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6098:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6099: 	    if ($imgsrc =~ m{^/res/}) {
                   6100: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6101: 		&Apache::lonnet::repcopy($local_name);
                   6102: 	    }
                   6103: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6104:         }
                   6105:         my $alttext = $domain;
                   6106:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6107:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6108:         }
                   6109:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6110:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6111:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6112:     } else {
1.60      matthew  6113:         return '';
1.59      www      6114:     }
                   6115: }
1.63      www      6116: ##############################################
                   6117: 
                   6118: =pod
                   6119: 
1.112     bowersj2 6120: =item * &designparm()
1.63      www      6121: 
                   6122: Inputs: $which parameter; $domain (usually will be undef)
                   6123: 
                   6124: Returns: value of designparamter $which
                   6125: 
                   6126: =cut
1.112     bowersj2 6127: 
1.397     albertel 6128: 
1.400     albertel 6129: ##############################################
1.397     albertel 6130: sub designparm {
                   6131:     my ($which,$domain)=@_;
                   6132:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6133:         return $env{'environment.color.'.$which};
1.96      www      6134:     }
1.63      www      6135:     $domain=&determinedomain($domain);
1.1016    raeburn  6136:     my %domdesign;
                   6137:     unless ($domain eq 'public') {
                   6138:         %domdesign = &get_domainconf($domain);
                   6139:     }
1.520     raeburn  6140:     my $output;
1.517     raeburn  6141:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6142:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6143:     } else {
1.520     raeburn  6144:         $output = $defaultdesign{$which};
                   6145:     }
                   6146:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6147:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6148:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6149:             if ($output =~ m{^/res/}) {
                   6150:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6151:                 &Apache::lonnet::repcopy($local_name);
                   6152:             }
1.520     raeburn  6153:             $output = &lonhttpdurl($output);
                   6154:         }
1.63      www      6155:     }
1.520     raeburn  6156:     return $output;
1.63      www      6157: }
1.59      www      6158: 
1.822     bisitz   6159: ##############################################
                   6160: =pod
                   6161: 
1.832     bisitz   6162: =item * &authorspace()
                   6163: 
1.1028    raeburn  6164: Inputs: $url (usually will be undef).
1.832     bisitz   6165: 
1.1132    raeburn  6166: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6167:          directory being viewed (or for which action is being taken). 
                   6168:          If $url is provided, and begins /priv/<domain>/<uname>
                   6169:          the path will be that portion of the $context argument.
                   6170:          Otherwise the path will be for the author space of the current
                   6171:          user when the current role is author, or for that of the 
                   6172:          co-author/assistant co-author space when the current role 
                   6173:          is co-author or assistant co-author.
1.832     bisitz   6174: 
                   6175: =cut
                   6176: 
                   6177: sub authorspace {
1.1028    raeburn  6178:     my ($url) = @_;
                   6179:     if ($url ne '') {
                   6180:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6181:            return $1;
                   6182:         }
                   6183:     }
1.832     bisitz   6184:     my $caname = '';
1.1024    www      6185:     my $cadom = '';
1.1028    raeburn  6186:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6187:         ($cadom,$caname) =
1.832     bisitz   6188:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6189:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6190:         $caname = $env{'user.name'};
1.1024    www      6191:         $cadom = $env{'user.domain'};
1.832     bisitz   6192:     }
1.1028    raeburn  6193:     if (($caname ne '') && ($cadom ne '')) {
                   6194:         return "/priv/$cadom/$caname/";
                   6195:     }
                   6196:     return;
1.832     bisitz   6197: }
                   6198: 
                   6199: ##############################################
                   6200: =pod
                   6201: 
1.822     bisitz   6202: =item * &head_subbox()
                   6203: 
                   6204: Inputs: $content (contains HTML code with page functions, etc.)
                   6205: 
                   6206: Returns: HTML div with $content
                   6207:          To be included in page header
                   6208: 
                   6209: =cut
                   6210: 
                   6211: sub head_subbox {
                   6212:     my ($content)=@_;
                   6213:     my $output =
1.993     raeburn  6214:         '<div class="LC_head_subbox">'
1.822     bisitz   6215:        .$content
                   6216:        .'</div>'
                   6217: }
                   6218: 
                   6219: ##############################################
                   6220: =pod
                   6221: 
                   6222: =item * &CSTR_pageheader()
                   6223: 
1.1026    raeburn  6224: Input: (optional) filename from which breadcrumb trail is built.
                   6225:        In most cases no input as needed, as $env{'request.filename'}
                   6226:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   6227: 
                   6228: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6229:          To be included on Authoring Space pages
1.822     bisitz   6230: 
                   6231: =cut
                   6232: 
                   6233: sub CSTR_pageheader {
1.1026    raeburn  6234:     my ($trailfile) = @_;
                   6235:     if ($trailfile eq '') {
                   6236:         $trailfile = $env{'request.filename'};
                   6237:     }
                   6238: 
                   6239: # this is for resources; directories have customtitle, and crumbs
                   6240: # and select recent are created in lonpubdir.pm
                   6241: 
                   6242:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6243:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6244:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6245:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6246:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6247: 
                   6248:     my $parentpath = '';
                   6249:     my $lastitem = '';
                   6250:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6251:         $parentpath = $1;
                   6252:         $lastitem = $2;
                   6253:     } else {
                   6254:         $lastitem = $thisdisfn;
                   6255:     }
1.921     bisitz   6256: 
1.1246    raeburn  6257:     my ($crsauthor,$title);
                   6258:     if (($env{'request.course.id'}) &&
                   6259:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6260:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6261:         $crsauthor = 1;
                   6262:         $title = &mt('Course Authoring Space');
                   6263:     } else {
                   6264:         $title = &mt('Authoring Space');
                   6265:     }
                   6266: 
1.1314    raeburn  6267:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  6268:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6269:         $target = '';
                   6270:         $crumbtarget = '';
1.1313    raeburn  6271:     }
                   6272: 
1.921     bisitz   6273:     my $output =
1.822     bisitz   6274:          '<div>'
                   6275:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6276:         .'<b>'.$title.'</b> '
1.1314    raeburn  6277:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6278:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6279: 
                   6280:     if ($lastitem) {
                   6281:         $output .=
                   6282:              '<span class="LC_filename">'
                   6283:             .$lastitem
                   6284:             .'</span>';
                   6285:     }
1.1245    raeburn  6286: 
1.1246    raeburn  6287:     if ($crsauthor) {
                   6288:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   6289:     } else {
                   6290:         $output .=
                   6291:              '<br />'
1.1314    raeburn  6292:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6293:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6294:             .'</form>'
                   6295:             .&Apache::lonmenu::constspaceform();
                   6296:     }
                   6297:     $output .= '</div>';
1.921     bisitz   6298: 
                   6299:     return $output;
1.822     bisitz   6300: }
                   6301: 
1.60      matthew  6302: ###############################################
                   6303: ###############################################
                   6304: 
                   6305: =pod
                   6306: 
1.112     bowersj2 6307: =back
                   6308: 
1.549     albertel 6309: =head1 HTML Helpers
1.112     bowersj2 6310: 
                   6311: =over 4
                   6312: 
                   6313: =item * &bodytag()
1.60      matthew  6314: 
                   6315: Returns a uniform header for LON-CAPA web pages.
                   6316: 
                   6317: Inputs: 
                   6318: 
1.112     bowersj2 6319: =over 4
                   6320: 
                   6321: =item * $title, A title to be displayed on the page.
                   6322: 
                   6323: =item * $function, the current role (can be undef).
                   6324: 
                   6325: =item * $addentries, extra parameters for the <body> tag.
                   6326: 
                   6327: =item * $bodyonly, if defined, only return the <body> tag.
                   6328: 
                   6329: =item * $domain, if defined, force a given domain.
                   6330: 
                   6331: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6332:             text interface only)
1.60      matthew  6333: 
1.814     bisitz   6334: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6335:                      navigational links
1.317     albertel 6336: 
1.338     albertel 6337: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6338: 
1.460     albertel 6339: =item * $args, optional argument valid values are
                   6340:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6341:             use_absolute     -> for external resource or syllabus, this will
                   6342:                                 contain https://<hostname> if server uses
                   6343:                                 https (as per hosts.tab), but request is for http
                   6344:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6345: 
1.1096    raeburn  6346: =item * $advtoolsref, optional argument, ref to an array containing
                   6347:             inlineremote items to be added in "Functions" menu below
                   6348:             breadcrumbs.
                   6349: 
1.1316    raeburn  6350: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6351:             course, if LON-CAPA is in LTI Provider context. Value is
                   6352:             the scope of use, i.e., launch was for access to a single, a map
                   6353:             or the entire course.
                   6354: 
                   6355: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6356:             context, this will contain the URL for the landing item in
                   6357:             the course, after launch from an LTI Consumer
                   6358: 
1.1318    raeburn  6359: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6360:             context, this will contain a reference to hash of items
                   6361:             to be included in the page header and/or inline menu.
                   6362: 
1.112     bowersj2 6363: =back
                   6364: 
1.60      matthew  6365: Returns: A uniform header for LON-CAPA web pages.  
                   6366: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6367: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6368: other decorations will be returned.
                   6369: 
                   6370: =cut
                   6371: 
1.54      www      6372: sub bodytag {
1.831     bisitz   6373:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6374:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
                   6375:         $ltimenu,$menucoll,$menuref)=@_;
1.339     albertel 6376: 
1.954     raeburn  6377:     my $public;
                   6378:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6379:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6380:         $public = 1;
                   6381:     }
1.460     albertel 6382:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6383:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6384:     my $hostname = $args->{'hostname'};
1.339     albertel 6385: 
1.183     matthew  6386:     $function = &get_users_function() if (!$function);
1.339     albertel 6387:     my $img =    &designparm($function.'.img',$domain);
                   6388:     my $font =   &designparm($function.'.font',$domain);
                   6389:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6390: 
1.803     bisitz   6391:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6392: 		   'bgcolor' => $pgbg,
1.339     albertel 6393: 		   'text'    => $font,
                   6394:                    'alink'   => &designparm($function.'.alink',$domain),
                   6395: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6396: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6397:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6398: 
1.63      www      6399:  # role and realm
1.1178    raeburn  6400:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6401:     if ($realm) {
                   6402:         $realm = '/'.$realm;
                   6403:     }
1.1357    raeburn  6404:     if ($role eq 'ca') {
1.479     albertel 6405:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6406:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6407:     } 
1.55      www      6408: # realm
1.1357    raeburn  6409:     my ($cid,$sec);
1.258     albertel 6410:     if ($env{'request.course.id'}) {
1.1357    raeburn  6411:         $cid = $env{'request.course.id'};
                   6412:         if ($env{'request.course.sec'}) {
                   6413:             $sec = $env{'request.course.sec'};
                   6414:         }
                   6415:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6416:         if (&Apache::lonnet::is_course($1,$2)) {
                   6417:             $cid = $1.'_'.$2;
                   6418:             $sec = $3;
                   6419:         }
                   6420:     }
                   6421:     if ($cid) {
1.378     raeburn  6422:         if ($env{'request.role'} !~ /^cr/) {
                   6423:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6424:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6425:             if ($env{'request.role.desc'}) {
                   6426:                 $role = $env{'request.role.desc'};
                   6427:             } else {
                   6428:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6429:             }
1.1257    raeburn  6430:         } else {
                   6431:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6432:         }
1.1357    raeburn  6433:         if ($sec) {
                   6434:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6435:         }   
1.1357    raeburn  6436: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6437:     } else {
                   6438:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6439:     }
1.433     albertel 6440: 
1.359     albertel 6441:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6442: 
1.438     albertel 6443:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6444: 
1.101     www      6445: # construct main body tag
1.359     albertel 6446:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6447: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6448: 
1.1131    raeburn  6449:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6450: 
1.1130    raeburn  6451:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6452:         return $bodytag;
1.1130    raeburn  6453:     }
1.359     albertel 6454: 
1.954     raeburn  6455:     if ($public) {
1.433     albertel 6456: 	undef($role);
                   6457:     }
1.1318    raeburn  6458: 
1.1359    raeburn  6459:     my $showcrstitle = 1;
1.1357    raeburn  6460:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6461:         if (ref($ltimenu) eq 'HASH') {
                   6462:             unless ($ltimenu->{'role'}) {
                   6463:                 undef($role);
                   6464:             }
                   6465:             unless ($ltimenu->{'coursetitle'}) {
                   6466:                 $realm='&nbsp;';
1.1359    raeburn  6467:                 $showcrstitle = 0;
                   6468:             }
                   6469:         }
                   6470:     } elsif (($cid) && ($menucoll)) {
                   6471:         if (ref($menuref) eq 'HASH') {
                   6472:             unless ($menuref->{'role'}) {
                   6473:                 undef($role);
                   6474:             }
                   6475:             unless ($menuref->{'crs'}) {
                   6476:                 $realm='&nbsp;';
                   6477:                 $showcrstitle = 0;
1.1318    raeburn  6478:             }
                   6479:         }
                   6480:     }
                   6481: 
1.762     bisitz   6482:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6483:     #
                   6484:     # Extra info if you are the DC
                   6485:     my $dc_info = '';
1.1359    raeburn  6486:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6487:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6488:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6489:         $dc_info =~ s/\s+$//;
1.359     albertel 6490:     }
                   6491: 
1.1237    raeburn  6492:     my $crstype;
1.1357    raeburn  6493:     if ($cid) {
                   6494:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6495:     } elsif ($args->{'crstype'}) {
                   6496:         $crstype = $args->{'crstype'};
                   6497:     }
                   6498:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6499:         undef($role);
                   6500:     } else {
1.1242    raeburn  6501:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6502:     }
1.853     droeschl 6503: 
1.903     droeschl 6504:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6505: 
                   6506:         #    if ($env{'request.state'} eq 'construct') {
                   6507:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6508:         #    }
                   6509: 
1.1130    raeburn  6510:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6511:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6512: 
1.1318    raeburn  6513:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6514:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
                   6515:                                                               $args->{'links_disabled'});
1.359     albertel 6516: 
1.1318    raeburn  6517:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6518:                 if ($dc_info) {
                   6519:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6520:                 }
                   6521:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6522:                                <em>$realm</em> $dc_info</div>|;
                   6523:                 return $bodytag;
                   6524:             }
1.894     droeschl 6525: 
1.1318    raeburn  6526:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6527:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6528:             }
1.916     droeschl 6529: 
1.1318    raeburn  6530:             $bodytag .= $right;
1.852     droeschl 6531: 
1.1318    raeburn  6532:             if ($dc_info) {
                   6533:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6534:             }
                   6535:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6536:         }
1.916     droeschl 6537: 
1.1169    raeburn  6538:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6539:         if ($args->{'no_secondary_menu'}) {
                   6540:             return $bodytag;
                   6541:         }
1.1169    raeburn  6542:         #don't show menus for public users
1.954     raeburn  6543:         if (!$public){
1.1318    raeburn  6544:             unless ($args->{'no_inline_menu'}) {
                   6545:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6546:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6547:                                                             $menucoll,$menuref,
                   6548:                                                             $args->{'links_disabled'});
1.1318    raeburn  6549:             }
1.903     droeschl 6550:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6551:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6552:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6553:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6554:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6555:             } elsif ($forcereg) {
                   6556:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6557:                                                             $args->{'group'},
1.1274    raeburn  6558:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6559:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6560:             } else {
                   6561:                 $bodytag .= 
                   6562:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6563:                                                         $forcereg,$args->{'group'},
                   6564:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6565:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6566:             }
1.903     droeschl 6567:         }else{
                   6568:             # this is to seperate menu from content when there's no secondary
                   6569:             # menu. Especially needed for public accessible ressources.
                   6570:             $bodytag .= '<hr style="clear:both" />';
                   6571:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6572:         }
1.903     droeschl 6573: 
1.235     raeburn  6574:         return $bodytag;
1.182     matthew  6575: }
                   6576: 
1.917     raeburn  6577: sub dc_courseid_toggle {
                   6578:     my ($dc_info) = @_;
1.980     raeburn  6579:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6580:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6581:            &mt('(More ...)').'</a></span>'.
                   6582:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6583: }
                   6584: 
1.330     albertel 6585: sub make_attr_string {
                   6586:     my ($register,$attr_ref) = @_;
                   6587: 
                   6588:     if ($attr_ref && !ref($attr_ref)) {
                   6589: 	die("addentries Must be a hash ref ".
                   6590: 	    join(':',caller(1))." ".
                   6591: 	    join(':',caller(0))." ");
                   6592:     }
                   6593: 
                   6594:     if ($register) {
1.339     albertel 6595: 	my ($on_load,$on_unload);
                   6596: 	foreach my $key (keys(%{$attr_ref})) {
                   6597: 	    if      (lc($key) eq 'onload') {
                   6598: 		$on_load.=$attr_ref->{$key}.';';
                   6599: 		delete($attr_ref->{$key});
                   6600: 
                   6601: 	    } elsif (lc($key) eq 'onunload') {
                   6602: 		$on_unload.=$attr_ref->{$key}.';';
                   6603: 		delete($attr_ref->{$key});
                   6604: 	    }
                   6605: 	}
1.953     droeschl 6606: 	$attr_ref->{'onload'}  = $on_load;
                   6607: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6608:     }
1.339     albertel 6609: 
1.330     albertel 6610:     my $attr_string;
1.1159    raeburn  6611:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6612: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6613:     }
                   6614:     return $attr_string;
                   6615: }
                   6616: 
                   6617: 
1.182     matthew  6618: ###############################################
1.251     albertel 6619: ###############################################
                   6620: 
                   6621: =pod
                   6622: 
                   6623: =item * &endbodytag()
                   6624: 
                   6625: Returns a uniform footer for LON-CAPA web pages.
                   6626: 
1.635     raeburn  6627: Inputs: 1 - optional reference to an args hash
                   6628: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6629: a 'Continue' link is not displayed if the page contains an
                   6630: internal redirect in the <head></head> section,
                   6631: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6632: 
                   6633: =cut
                   6634: 
                   6635: sub endbodytag {
1.635     raeburn  6636:     my ($args) = @_;
1.1080    raeburn  6637:     my $endbodytag;
                   6638:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6639:         $endbodytag='</body>';
                   6640:     }
1.315     albertel 6641:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6642:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6643: 	    $endbodytag=
                   6644: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6645: 	        &mt('Continue').'</a>'.
                   6646: 	        $endbodytag;
                   6647:         }
1.315     albertel 6648:     }
1.251     albertel 6649:     return $endbodytag;
                   6650: }
                   6651: 
1.352     albertel 6652: =pod
                   6653: 
                   6654: =item * &standard_css()
                   6655: 
                   6656: Returns a style sheet
                   6657: 
                   6658: Inputs: (all optional)
                   6659:             domain         -> force to color decorate a page for a specific
                   6660:                                domain
                   6661:             function       -> force usage of a specific rolish color scheme
                   6662:             bgcolor        -> override the default page bgcolor
                   6663: 
                   6664: =cut
                   6665: 
1.343     albertel 6666: sub standard_css {
1.345     albertel 6667:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6668:     $function  = &get_users_function() if (!$function);
                   6669:     my $img    = &designparm($function.'.img',   $domain);
                   6670:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6671:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6672:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6673: #second colour for later usage
1.345     albertel 6674:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6675:     my $pgbg_or_bgcolor =
                   6676: 	         $bgcolor ||
1.352     albertel 6677: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6678:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6679:     my $alink  = &designparm($function.'.alink', $domain);
                   6680:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6681:     my $link   = &designparm($function.'.link',  $domain);
                   6682: 
1.602     albertel 6683:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6684:     my $mono                 = 'monospace';
1.850     bisitz   6685:     my $data_table_head      = $sidebg;
                   6686:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6687:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6688:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6689:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6690:     my $mail_new             = '#FFBB77';
                   6691:     my $mail_new_hover       = '#DD9955';
                   6692:     my $mail_read            = '#BBBB77';
                   6693:     my $mail_read_hover      = '#999944';
                   6694:     my $mail_replied         = '#AAAA88';
                   6695:     my $mail_replied_hover   = '#888855';
                   6696:     my $mail_other           = '#99BBBB';
                   6697:     my $mail_other_hover     = '#669999';
1.391     albertel 6698:     my $table_header         = '#DDDDDD';
1.489     raeburn  6699:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6700:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6701:     my $button_hover         = '#BF2317';
1.392     albertel 6702: 
1.608     albertel 6703:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6704:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6705:                                              : '0 3px 0 4px';
1.448     albertel 6706: 
1.523     albertel 6707: 
1.343     albertel 6708:     return <<END;
1.947     droeschl 6709: 
                   6710: /* needed for iframe to allow 100% height in FF */
                   6711: body, html { 
                   6712:     margin: 0;
                   6713:     padding: 0 0.5%;
                   6714:     height: 99%; /* to avoid scrollbars */
                   6715: }
                   6716: 
1.795     www      6717: body {
1.911     bisitz   6718:   font-family: $sans;
                   6719:   line-height:130%;
                   6720:   font-size:0.83em;
                   6721:   color:$font;
1.795     www      6722: }
                   6723: 
1.959     onken    6724: a:focus,
                   6725: a:focus img {
1.795     www      6726:   color: red;
                   6727: }
1.698     harmsja  6728: 
1.911     bisitz   6729: form, .inline {
                   6730:   display: inline;
1.795     www      6731: }
1.721     harmsja  6732: 
1.795     www      6733: .LC_right {
1.911     bisitz   6734:   text-align:right;
1.795     www      6735: }
                   6736: 
                   6737: .LC_middle {
1.911     bisitz   6738:   vertical-align:middle;
1.795     www      6739: }
1.721     harmsja  6740: 
1.1130    raeburn  6741: .LC_floatleft {
                   6742:   float: left;
                   6743: }
                   6744: 
                   6745: .LC_floatright {
                   6746:   float: right;
                   6747: }
                   6748: 
1.911     bisitz   6749: .LC_400Box {
                   6750:   width:400px;
                   6751: }
1.721     harmsja  6752: 
1.947     droeschl 6753: .LC_iframecontainer {
                   6754:     width: 98%;
                   6755:     margin: 0;
                   6756:     position: fixed;
                   6757:     top: 8.5em;
                   6758:     bottom: 0;
                   6759: }
                   6760: 
                   6761: .LC_iframecontainer iframe{
                   6762:     border: none;
                   6763:     width: 100%;
                   6764:     height: 100%;
                   6765: }
                   6766: 
1.778     bisitz   6767: .LC_filename {
                   6768:   font-family: $mono;
                   6769:   white-space:pre;
1.921     bisitz   6770:   font-size: 120%;
1.778     bisitz   6771: }
                   6772: 
                   6773: .LC_fileicon {
                   6774:   border: none;
                   6775:   height: 1.3em;
                   6776:   vertical-align: text-bottom;
                   6777:   margin-right: 0.3em;
                   6778:   text-decoration:none;
                   6779: }
                   6780: 
1.1008    www      6781: .LC_setting {
                   6782:   text-decoration:underline;
                   6783: }
                   6784: 
1.350     albertel 6785: .LC_error {
                   6786:   color: red;
                   6787: }
1.795     www      6788: 
1.1097    bisitz   6789: .LC_warning {
                   6790:   color: darkorange;
                   6791: }
                   6792: 
1.457     albertel 6793: .LC_diff_removed {
1.733     bisitz   6794:   color: red;
1.394     albertel 6795: }
1.532     albertel 6796: 
                   6797: .LC_info,
1.457     albertel 6798: .LC_success,
                   6799: .LC_diff_added {
1.350     albertel 6800:   color: green;
                   6801: }
1.795     www      6802: 
1.802     bisitz   6803: div.LC_confirm_box {
                   6804:   background-color: #FAFAFA;
                   6805:   border: 1px solid $lg_border_color;
                   6806:   margin-right: 0;
                   6807:   padding: 5px;
                   6808: }
                   6809: 
                   6810: div.LC_confirm_box .LC_error img,
                   6811: div.LC_confirm_box .LC_success img {
                   6812:   vertical-align: middle;
                   6813: }
                   6814: 
1.1242    raeburn  6815: .LC_maxwidth {
                   6816:   max-width: 100%;
                   6817:   height: auto;
                   6818: }
                   6819: 
1.1243    raeburn  6820: .LC_textsize_mobile {
                   6821:   \@media only screen and (max-device-width: 480px) {
                   6822:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6823:   }
                   6824: }
                   6825: 
1.440     albertel 6826: .LC_icon {
1.771     droeschl 6827:   border: none;
1.790     droeschl 6828:   vertical-align: middle;
1.771     droeschl 6829: }
                   6830: 
1.543     albertel 6831: .LC_docs_spacer {
                   6832:   width: 25px;
                   6833:   height: 1px;
1.771     droeschl 6834:   border: none;
1.543     albertel 6835: }
1.346     albertel 6836: 
1.532     albertel 6837: .LC_internal_info {
1.735     bisitz   6838:   color: #999999;
1.532     albertel 6839: }
                   6840: 
1.794     www      6841: .LC_discussion {
1.1050    www      6842:   background: $data_table_dark;
1.911     bisitz   6843:   border: 1px solid black;
                   6844:   margin: 2px;
1.794     www      6845: }
                   6846: 
                   6847: .LC_disc_action_left {
1.1050    www      6848:   background: $sidebg;
1.911     bisitz   6849:   text-align: left;
1.1050    www      6850:   padding: 4px;
                   6851:   margin: 2px;
1.794     www      6852: }
                   6853: 
                   6854: .LC_disc_action_right {
1.1050    www      6855:   background: $sidebg;
1.911     bisitz   6856:   text-align: right;
1.1050    www      6857:   padding: 4px;
                   6858:   margin: 2px;
1.794     www      6859: }
                   6860: 
                   6861: .LC_disc_new_item {
1.911     bisitz   6862:   background: white;
                   6863:   border: 2px solid red;
1.1050    www      6864:   margin: 4px;
                   6865:   padding: 4px;
1.794     www      6866: }
                   6867: 
                   6868: .LC_disc_old_item {
1.911     bisitz   6869:   background: white;
1.1050    www      6870:   margin: 4px;
                   6871:   padding: 4px;
1.794     www      6872: }
                   6873: 
1.458     albertel 6874: table.LC_pastsubmission {
                   6875:   border: 1px solid black;
                   6876:   margin: 2px;
                   6877: }
                   6878: 
1.924     bisitz   6879: table#LC_menubuttons {
1.345     albertel 6880:   width: 100%;
                   6881:   background: $pgbg;
1.392     albertel 6882:   border: 2px;
1.402     albertel 6883:   border-collapse: separate;
1.803     bisitz   6884:   padding: 0;
1.345     albertel 6885: }
1.392     albertel 6886: 
1.801     tempelho 6887: table#LC_title_bar a {
                   6888:   color: $fontmenu;
                   6889: }
1.836     bisitz   6890: 
1.807     droeschl 6891: table#LC_title_bar {
1.819     tempelho 6892:   clear: both;
1.836     bisitz   6893:   display: none;
1.807     droeschl 6894: }
                   6895: 
1.795     www      6896: table#LC_title_bar,
1.933     droeschl 6897: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6898: table#LC_title_bar.LC_with_remote {
1.359     albertel 6899:   width: 100%;
1.392     albertel 6900:   border-color: $pgbg;
                   6901:   border-style: solid;
                   6902:   border-width: $border;
1.379     albertel 6903:   background: $pgbg;
1.801     tempelho 6904:   color: $fontmenu;
1.392     albertel 6905:   border-collapse: collapse;
1.803     bisitz   6906:   padding: 0;
1.819     tempelho 6907:   margin: 0;
1.359     albertel 6908: }
1.795     www      6909: 
1.933     droeschl 6910: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6911:     margin: 0;
                   6912:     padding: 0;
1.933     droeschl 6913:     position: relative;
                   6914:     list-style: none;
1.913     droeschl 6915: }
1.933     droeschl 6916: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6917:     display: inline;
                   6918: }
1.933     droeschl 6919: 
                   6920: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6921:     padding: 0;
1.933     droeschl 6922:     margin: 0;
                   6923:     float: left;
1.913     droeschl 6924: }
1.933     droeschl 6925: .LC_breadcrumb_tools_tools {
                   6926:     padding: 0;
                   6927:     margin: 0;
1.913     droeschl 6928:     float: right;
                   6929: }
                   6930: 
1.1240    raeburn  6931: .LC_placement_prog {
                   6932:     padding-right: 20px;
                   6933:     font-weight: bold;
                   6934:     font-size: 90%;
                   6935: }
                   6936: 
1.359     albertel 6937: table#LC_title_bar td {
                   6938:   background: $tabbg;
                   6939: }
1.795     www      6940: 
1.911     bisitz   6941: table#LC_menubuttons img {
1.803     bisitz   6942:   border: none;
1.346     albertel 6943: }
1.795     www      6944: 
1.842     droeschl 6945: .LC_breadcrumbs_component {
1.911     bisitz   6946:   float: right;
                   6947:   margin: 0 1em;
1.357     albertel 6948: }
1.842     droeschl 6949: .LC_breadcrumbs_component img {
1.911     bisitz   6950:   vertical-align: middle;
1.777     tempelho 6951: }
1.795     www      6952: 
1.1243    raeburn  6953: .LC_breadcrumbs_hoverable {
                   6954:   background: $sidebg;
                   6955: }
                   6956: 
1.383     albertel 6957: td.LC_table_cell_checkbox {
                   6958:   text-align: center;
                   6959: }
1.795     www      6960: 
                   6961: .LC_fontsize_small {
1.911     bisitz   6962:   font-size: 70%;
1.705     tempelho 6963: }
                   6964: 
1.844     bisitz   6965: #LC_breadcrumbs {
1.911     bisitz   6966:   clear:both;
                   6967:   background: $sidebg;
                   6968:   border-bottom: 1px solid $lg_border_color;
                   6969:   line-height: 2.5em;
1.933     droeschl 6970:   overflow: hidden;
1.911     bisitz   6971:   margin: 0;
                   6972:   padding: 0;
1.995     raeburn  6973:   text-align: left;
1.819     tempelho 6974: }
1.862     bisitz   6975: 
1.1098    bisitz   6976: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6977:   clear:both;
                   6978:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6979:   border: 1px solid $sidebg;
1.1098    bisitz   6980:   margin: 0 0 10px 0;
1.966     bisitz   6981:   padding: 3px;
1.995     raeburn  6982:   text-align: left;
1.822     bisitz   6983: }
                   6984: 
1.795     www      6985: .LC_fontsize_medium {
1.911     bisitz   6986:   font-size: 85%;
1.705     tempelho 6987: }
                   6988: 
1.795     www      6989: .LC_fontsize_large {
1.911     bisitz   6990:   font-size: 120%;
1.705     tempelho 6991: }
                   6992: 
1.346     albertel 6993: .LC_menubuttons_inline_text {
                   6994:   color: $font;
1.698     harmsja  6995:   font-size: 90%;
1.701     harmsja  6996:   padding-left:3px;
1.346     albertel 6997: }
                   6998: 
1.934     droeschl 6999: .LC_menubuttons_inline_text img{
                   7000:   vertical-align: middle;
                   7001: }
                   7002: 
1.1051    www      7003: li.LC_menubuttons_inline_text img {
1.951     onken    7004:   cursor:pointer;
1.1002    droeschl 7005:   text-decoration: none;
1.951     onken    7006: }
                   7007: 
1.526     www      7008: .LC_menubuttons_link {
                   7009:   text-decoration: none;
                   7010: }
1.795     www      7011: 
1.522     albertel 7012: .LC_menubuttons_category {
1.521     www      7013:   color: $font;
1.526     www      7014:   background: $pgbg;
1.521     www      7015:   font-size: larger;
                   7016:   font-weight: bold;
                   7017: }
                   7018: 
1.346     albertel 7019: td.LC_menubuttons_text {
1.911     bisitz   7020:   color: $font;
1.346     albertel 7021: }
1.706     harmsja  7022: 
1.346     albertel 7023: .LC_current_location {
                   7024:   background: $tabbg;
                   7025: }
1.795     www      7026: 
1.1286    raeburn  7027: td.LC_zero_height {
                   7028:   line-height: 0; 
                   7029:   cellpadding: 0;
                   7030: }
                   7031: 
1.938     bisitz   7032: table.LC_data_table {
1.347     albertel 7033:   border: 1px solid #000000;
1.402     albertel 7034:   border-collapse: separate;
1.426     albertel 7035:   border-spacing: 1px;
1.610     albertel 7036:   background: $pgbg;
1.347     albertel 7037: }
1.795     www      7038: 
1.422     albertel 7039: .LC_data_table_dense {
                   7040:   font-size: small;
                   7041: }
1.795     www      7042: 
1.507     raeburn  7043: table.LC_nested_outer {
                   7044:   border: 1px solid #000000;
1.589     raeburn  7045:   border-collapse: collapse;
1.803     bisitz   7046:   border-spacing: 0;
1.507     raeburn  7047:   width: 100%;
                   7048: }
1.795     www      7049: 
1.879     raeburn  7050: table.LC_innerpickbox,
1.507     raeburn  7051: table.LC_nested {
1.803     bisitz   7052:   border: none;
1.589     raeburn  7053:   border-collapse: collapse;
1.803     bisitz   7054:   border-spacing: 0;
1.507     raeburn  7055:   width: 100%;
                   7056: }
1.795     www      7057: 
1.911     bisitz   7058: table.LC_data_table tr th,
                   7059: table.LC_calendar tr th,
1.879     raeburn  7060: table.LC_prior_tries tr th,
                   7061: table.LC_innerpickbox tr th {
1.349     albertel 7062:   font-weight: bold;
                   7063:   background-color: $data_table_head;
1.801     tempelho 7064:   color:$fontmenu;
1.701     harmsja  7065:   font-size:90%;
1.347     albertel 7066: }
1.795     www      7067: 
1.879     raeburn  7068: table.LC_innerpickbox tr th,
                   7069: table.LC_innerpickbox tr td {
                   7070:   vertical-align: top;
                   7071: }
                   7072: 
1.711     raeburn  7073: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7074:   background-color: #CCCCCC;
1.711     raeburn  7075:   font-weight: bold;
                   7076:   text-align: left;
                   7077: }
1.795     www      7078: 
1.912     bisitz   7079: table.LC_data_table tr.LC_odd_row > td {
                   7080:   background-color: $data_table_light;
                   7081:   padding: 2px;
                   7082:   vertical-align: top;
                   7083: }
                   7084: 
1.809     bisitz   7085: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7086:   background-color: $data_table_light;
1.912     bisitz   7087:   vertical-align: top;
                   7088: }
                   7089: 
                   7090: table.LC_data_table tr.LC_even_row > td {
                   7091:   background-color: $data_table_dark;
1.425     albertel 7092:   padding: 2px;
1.900     bisitz   7093:   vertical-align: top;
1.347     albertel 7094: }
1.795     www      7095: 
1.809     bisitz   7096: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7097:   background-color: $data_table_dark;
1.900     bisitz   7098:   vertical-align: top;
1.347     albertel 7099: }
1.795     www      7100: 
1.425     albertel 7101: table.LC_data_table tr.LC_data_table_highlight td {
                   7102:   background-color: $data_table_darker;
                   7103: }
1.795     www      7104: 
1.639     raeburn  7105: table.LC_data_table tr td.LC_leftcol_header {
                   7106:   background-color: $data_table_head;
                   7107:   font-weight: bold;
                   7108: }
1.795     www      7109: 
1.451     albertel 7110: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7111: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7112:   font-weight: bold;
                   7113:   font-style: italic;
                   7114:   text-align: center;
                   7115:   padding: 8px;
1.347     albertel 7116: }
1.795     www      7117: 
1.1114    raeburn  7118: table.LC_data_table tr.LC_empty_row td,
                   7119: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7120:   background-color: $sidebg;
                   7121: }
                   7122: 
                   7123: table.LC_nested tr.LC_empty_row td {
                   7124:   background-color: #FFFFFF;
                   7125: }
                   7126: 
1.890     droeschl 7127: table.LC_caption {
                   7128: }
                   7129: 
1.507     raeburn  7130: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7131:   padding: 4ex
                   7132: }
1.795     www      7133: 
1.507     raeburn  7134: table.LC_nested_outer tr th {
                   7135:   font-weight: bold;
1.801     tempelho 7136:   color:$fontmenu;
1.507     raeburn  7137:   background-color: $data_table_head;
1.701     harmsja  7138:   font-size: small;
1.507     raeburn  7139:   border-bottom: 1px solid #000000;
                   7140: }
1.795     www      7141: 
1.507     raeburn  7142: table.LC_nested_outer tr td.LC_subheader {
                   7143:   background-color: $data_table_head;
                   7144:   font-weight: bold;
                   7145:   font-size: small;
                   7146:   border-bottom: 1px solid #000000;
                   7147:   text-align: right;
1.451     albertel 7148: }
1.795     www      7149: 
1.507     raeburn  7150: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7151:   background-color: #CCCCCC;
1.451     albertel 7152:   font-weight: bold;
                   7153:   font-size: small;
1.507     raeburn  7154:   text-align: center;
                   7155: }
1.795     www      7156: 
1.589     raeburn  7157: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7158: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7159:   text-align: left;
1.451     albertel 7160: }
1.795     www      7161: 
1.507     raeburn  7162: table.LC_nested td {
1.735     bisitz   7163:   background-color: #FFFFFF;
1.451     albertel 7164:   font-size: small;
1.507     raeburn  7165: }
1.795     www      7166: 
1.507     raeburn  7167: table.LC_nested_outer tr th.LC_right_item,
                   7168: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7169: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7170: table.LC_nested tr td.LC_right_item {
1.451     albertel 7171:   text-align: right;
                   7172: }
                   7173: 
1.507     raeburn  7174: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7175:   background-color: #EEEEEE;
1.451     albertel 7176: }
                   7177: 
1.473     raeburn  7178: table.LC_createuser {
                   7179: }
                   7180: 
                   7181: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7182:   font-size: small;
1.473     raeburn  7183: }
                   7184: 
                   7185: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7186:   background-color: #CCCCCC;
1.473     raeburn  7187:   font-weight: bold;
                   7188:   text-align: center;
                   7189: }
                   7190: 
1.349     albertel 7191: table.LC_calendar {
                   7192:   border: 1px solid #000000;
                   7193:   border-collapse: collapse;
1.917     raeburn  7194:   width: 98%;
1.349     albertel 7195: }
1.795     www      7196: 
1.349     albertel 7197: table.LC_calendar_pickdate {
                   7198:   font-size: xx-small;
                   7199: }
1.795     www      7200: 
1.349     albertel 7201: table.LC_calendar tr td {
                   7202:   border: 1px solid #000000;
                   7203:   vertical-align: top;
1.917     raeburn  7204:   width: 14%;
1.349     albertel 7205: }
1.795     www      7206: 
1.349     albertel 7207: table.LC_calendar tr td.LC_calendar_day_empty {
                   7208:   background-color: $data_table_dark;
                   7209: }
1.795     www      7210: 
1.779     bisitz   7211: table.LC_calendar tr td.LC_calendar_day_current {
                   7212:   background-color: $data_table_highlight;
1.777     tempelho 7213: }
1.795     www      7214: 
1.938     bisitz   7215: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7216:   background-color: $mail_new;
                   7217: }
1.795     www      7218: 
1.938     bisitz   7219: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7220:   background-color: $mail_new_hover;
                   7221: }
1.795     www      7222: 
1.938     bisitz   7223: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7224:   background-color: $mail_read;
                   7225: }
1.795     www      7226: 
1.938     bisitz   7227: /*
                   7228: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7229:   background-color: $mail_read_hover;
                   7230: }
1.938     bisitz   7231: */
1.795     www      7232: 
1.938     bisitz   7233: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7234:   background-color: $mail_replied;
                   7235: }
1.795     www      7236: 
1.938     bisitz   7237: /*
                   7238: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7239:   background-color: $mail_replied_hover;
                   7240: }
1.938     bisitz   7241: */
1.795     www      7242: 
1.938     bisitz   7243: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7244:   background-color: $mail_other;
                   7245: }
1.795     www      7246: 
1.938     bisitz   7247: /*
                   7248: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7249:   background-color: $mail_other_hover;
                   7250: }
1.938     bisitz   7251: */
1.494     raeburn  7252: 
1.777     tempelho 7253: table.LC_data_table tr > td.LC_browser_file,
                   7254: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7255:   background: #AAEE77;
1.389     albertel 7256: }
1.795     www      7257: 
1.777     tempelho 7258: table.LC_data_table tr > td.LC_browser_file_locked,
                   7259: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7260:   background: #FFAA99;
1.387     albertel 7261: }
1.795     www      7262: 
1.777     tempelho 7263: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7264:   background: #888888;
1.779     bisitz   7265: }
1.795     www      7266: 
1.777     tempelho 7267: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7268: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7269:   background: #F8F866;
1.777     tempelho 7270: }
1.795     www      7271: 
1.696     bisitz   7272: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7273:   background: #E0E8FF;
1.387     albertel 7274: }
1.696     bisitz   7275: 
1.707     bisitz   7276: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7277:   /* background: #77FF77; */
1.707     bisitz   7278: }
1.795     www      7279: 
1.707     bisitz   7280: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7281:   border-right: 8px solid #FFFF77;
1.707     bisitz   7282: }
1.795     www      7283: 
1.707     bisitz   7284: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7285:   border-right: 8px solid #FFAA77;
1.707     bisitz   7286: }
1.795     www      7287: 
1.707     bisitz   7288: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7289:   border-right: 8px solid #FF7777;
1.707     bisitz   7290: }
1.795     www      7291: 
1.707     bisitz   7292: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7293:   border-right: 8px solid #AAFF77;
1.707     bisitz   7294: }
1.795     www      7295: 
1.707     bisitz   7296: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7297:   border-right: 8px solid #11CC55;
1.707     bisitz   7298: }
                   7299: 
1.388     albertel 7300: span.LC_current_location {
1.701     harmsja  7301:   font-size:larger;
1.388     albertel 7302:   background: $pgbg;
                   7303: }
1.387     albertel 7304: 
1.1029    www      7305: span.LC_current_nav_location {
                   7306:   font-weight:bold;
                   7307:   background: $sidebg;
                   7308: }
                   7309: 
1.395     albertel 7310: span.LC_parm_menu_item {
                   7311:   font-size: larger;
                   7312: }
1.795     www      7313: 
1.395     albertel 7314: span.LC_parm_scope_all {
                   7315:   color: red;
                   7316: }
1.795     www      7317: 
1.395     albertel 7318: span.LC_parm_scope_folder {
                   7319:   color: green;
                   7320: }
1.795     www      7321: 
1.395     albertel 7322: span.LC_parm_scope_resource {
                   7323:   color: orange;
                   7324: }
1.795     www      7325: 
1.395     albertel 7326: span.LC_parm_part {
                   7327:   color: blue;
                   7328: }
1.795     www      7329: 
1.911     bisitz   7330: span.LC_parm_folder,
                   7331: span.LC_parm_symb {
1.395     albertel 7332:   font-size: x-small;
                   7333:   font-family: $mono;
                   7334:   color: #AAAAAA;
                   7335: }
                   7336: 
1.977     bisitz   7337: ul.LC_parm_parmlist li {
                   7338:   display: inline-block;
                   7339:   padding: 0.3em 0.8em;
                   7340:   vertical-align: top;
                   7341:   width: 150px;
                   7342:   border-top:1px solid $lg_border_color;
                   7343: }
                   7344: 
1.795     www      7345: td.LC_parm_overview_level_menu,
                   7346: td.LC_parm_overview_map_menu,
                   7347: td.LC_parm_overview_parm_selectors,
                   7348: td.LC_parm_overview_restrictions  {
1.396     albertel 7349:   border: 1px solid black;
                   7350:   border-collapse: collapse;
                   7351: }
1.795     www      7352: 
1.1285    raeburn  7353: span.LC_parm_recursive,
                   7354: td.LC_parm_recursive {
                   7355:   font-weight: bold;
                   7356:   font-size: smaller;
                   7357: }
                   7358: 
1.396     albertel 7359: table.LC_parm_overview_restrictions td {
                   7360:   border-width: 1px 4px 1px 4px;
                   7361:   border-style: solid;
                   7362:   border-color: $pgbg;
                   7363:   text-align: center;
                   7364: }
1.795     www      7365: 
1.396     albertel 7366: table.LC_parm_overview_restrictions th {
                   7367:   background: $tabbg;
                   7368:   border-width: 1px 4px 1px 4px;
                   7369:   border-style: solid;
                   7370:   border-color: $pgbg;
                   7371: }
1.795     www      7372: 
1.398     albertel 7373: table#LC_helpmenu {
1.803     bisitz   7374:   border: none;
1.398     albertel 7375:   height: 55px;
1.803     bisitz   7376:   border-spacing: 0;
1.398     albertel 7377: }
                   7378: 
                   7379: table#LC_helpmenu fieldset legend {
                   7380:   font-size: larger;
                   7381: }
1.795     www      7382: 
1.397     albertel 7383: table#LC_helpmenu_links {
                   7384:   width: 100%;
                   7385:   border: 1px solid black;
                   7386:   background: $pgbg;
1.803     bisitz   7387:   padding: 0;
1.397     albertel 7388:   border-spacing: 1px;
                   7389: }
1.795     www      7390: 
1.397     albertel 7391: table#LC_helpmenu_links tr td {
                   7392:   padding: 1px;
                   7393:   background: $tabbg;
1.399     albertel 7394:   text-align: center;
                   7395:   font-weight: bold;
1.397     albertel 7396: }
1.396     albertel 7397: 
1.795     www      7398: table#LC_helpmenu_links a:link,
                   7399: table#LC_helpmenu_links a:visited,
1.397     albertel 7400: table#LC_helpmenu_links a:active {
                   7401:   text-decoration: none;
                   7402:   color: $font;
                   7403: }
1.795     www      7404: 
1.397     albertel 7405: table#LC_helpmenu_links a:hover {
                   7406:   text-decoration: underline;
                   7407:   color: $vlink;
                   7408: }
1.396     albertel 7409: 
1.417     albertel 7410: .LC_chrt_popup_exists {
                   7411:   border: 1px solid #339933;
                   7412:   margin: -1px;
                   7413: }
1.795     www      7414: 
1.417     albertel 7415: .LC_chrt_popup_up {
                   7416:   border: 1px solid yellow;
                   7417:   margin: -1px;
                   7418: }
1.795     www      7419: 
1.417     albertel 7420: .LC_chrt_popup {
                   7421:   border: 1px solid #8888FF;
                   7422:   background: #CCCCFF;
                   7423: }
1.795     www      7424: 
1.421     albertel 7425: table.LC_pick_box {
                   7426:   border-collapse: separate;
                   7427:   background: white;
                   7428:   border: 1px solid black;
                   7429:   border-spacing: 1px;
                   7430: }
1.795     www      7431: 
1.421     albertel 7432: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7433:   background: $sidebg;
1.421     albertel 7434:   font-weight: bold;
1.900     bisitz   7435:   text-align: left;
1.740     bisitz   7436:   vertical-align: top;
1.421     albertel 7437:   width: 184px;
                   7438:   padding: 8px;
                   7439: }
1.795     www      7440: 
1.579     raeburn  7441: table.LC_pick_box td.LC_pick_box_value {
                   7442:   text-align: left;
                   7443:   padding: 8px;
                   7444: }
1.795     www      7445: 
1.579     raeburn  7446: table.LC_pick_box td.LC_pick_box_select {
                   7447:   text-align: left;
                   7448:   padding: 8px;
                   7449: }
1.795     www      7450: 
1.424     albertel 7451: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7452:   padding: 0;
1.421     albertel 7453:   height: 1px;
                   7454:   background: black;
                   7455: }
1.795     www      7456: 
1.421     albertel 7457: table.LC_pick_box td.LC_pick_box_submit {
                   7458:   text-align: right;
                   7459: }
1.795     www      7460: 
1.579     raeburn  7461: table.LC_pick_box td.LC_evenrow_value {
                   7462:   text-align: left;
                   7463:   padding: 8px;
                   7464:   background-color: $data_table_light;
                   7465: }
1.795     www      7466: 
1.579     raeburn  7467: table.LC_pick_box td.LC_oddrow_value {
                   7468:   text-align: left;
                   7469:   padding: 8px;
                   7470:   background-color: $data_table_light;
                   7471: }
1.795     www      7472: 
1.579     raeburn  7473: span.LC_helpform_receipt_cat {
                   7474:   font-weight: bold;
                   7475: }
1.795     www      7476: 
1.424     albertel 7477: table.LC_group_priv_box {
                   7478:   background: white;
                   7479:   border: 1px solid black;
                   7480:   border-spacing: 1px;
                   7481: }
1.795     www      7482: 
1.424     albertel 7483: table.LC_group_priv_box td.LC_pick_box_title {
                   7484:   background: $tabbg;
                   7485:   font-weight: bold;
                   7486:   text-align: right;
                   7487:   width: 184px;
                   7488: }
1.795     www      7489: 
1.424     albertel 7490: table.LC_group_priv_box td.LC_groups_fixed {
                   7491:   background: $data_table_light;
                   7492:   text-align: center;
                   7493: }
1.795     www      7494: 
1.424     albertel 7495: table.LC_group_priv_box td.LC_groups_optional {
                   7496:   background: $data_table_dark;
                   7497:   text-align: center;
                   7498: }
1.795     www      7499: 
1.424     albertel 7500: table.LC_group_priv_box td.LC_groups_functionality {
                   7501:   background: $data_table_darker;
                   7502:   text-align: center;
                   7503:   font-weight: bold;
                   7504: }
1.795     www      7505: 
1.424     albertel 7506: table.LC_group_priv td {
                   7507:   text-align: left;
1.803     bisitz   7508:   padding: 0;
1.424     albertel 7509: }
                   7510: 
                   7511: .LC_navbuttons {
                   7512:   margin: 2ex 0ex 2ex 0ex;
                   7513: }
1.795     www      7514: 
1.423     albertel 7515: .LC_topic_bar {
                   7516:   font-weight: bold;
                   7517:   background: $tabbg;
1.918     wenzelju 7518:   margin: 1em 0em 1em 2em;
1.805     bisitz   7519:   padding: 3px;
1.918     wenzelju 7520:   font-size: 1.2em;
1.423     albertel 7521: }
1.795     www      7522: 
1.423     albertel 7523: .LC_topic_bar span {
1.918     wenzelju 7524:   left: 0.5em;
                   7525:   position: absolute;
1.423     albertel 7526:   vertical-align: middle;
1.918     wenzelju 7527:   font-size: 1.2em;
1.423     albertel 7528: }
1.795     www      7529: 
1.423     albertel 7530: table.LC_course_group_status {
                   7531:   margin: 20px;
                   7532: }
1.795     www      7533: 
1.423     albertel 7534: table.LC_status_selector td {
                   7535:   vertical-align: top;
                   7536:   text-align: center;
1.424     albertel 7537:   padding: 4px;
                   7538: }
1.795     www      7539: 
1.599     albertel 7540: div.LC_feedback_link {
1.616     albertel 7541:   clear: both;
1.829     kalberla 7542:   background: $sidebg;
1.779     bisitz   7543:   width: 100%;
1.829     kalberla 7544:   padding-bottom: 10px;
                   7545:   border: 1px $tabbg solid;
1.833     kalberla 7546:   height: 22px;
                   7547:   line-height: 22px;
                   7548:   padding-top: 5px;
                   7549: }
                   7550: 
                   7551: div.LC_feedback_link img {
                   7552:   height: 22px;
1.867     kalberla 7553:   vertical-align:middle;
1.829     kalberla 7554: }
                   7555: 
1.911     bisitz   7556: div.LC_feedback_link a {
1.829     kalberla 7557:   text-decoration: none;
1.489     raeburn  7558: }
1.795     www      7559: 
1.867     kalberla 7560: div.LC_comblock {
1.911     bisitz   7561:   display:inline;
1.867     kalberla 7562:   color:$font;
                   7563:   font-size:90%;
                   7564: }
                   7565: 
                   7566: div.LC_feedback_link div.LC_comblock {
                   7567:   padding-left:5px;
                   7568: }
                   7569: 
                   7570: div.LC_feedback_link div.LC_comblock a {
                   7571:   color:$font;
                   7572: }
                   7573: 
1.489     raeburn  7574: span.LC_feedback_link {
1.858     bisitz   7575:   /* background: $feedback_link_bg; */
1.599     albertel 7576:   font-size: larger;
                   7577: }
1.795     www      7578: 
1.599     albertel 7579: span.LC_message_link {
1.858     bisitz   7580:   /* background: $feedback_link_bg; */
1.599     albertel 7581:   font-size: larger;
                   7582:   position: absolute;
                   7583:   right: 1em;
1.489     raeburn  7584: }
1.421     albertel 7585: 
1.515     albertel 7586: table.LC_prior_tries {
1.524     albertel 7587:   border: 1px solid #000000;
                   7588:   border-collapse: separate;
                   7589:   border-spacing: 1px;
1.515     albertel 7590: }
1.523     albertel 7591: 
1.515     albertel 7592: table.LC_prior_tries td {
1.524     albertel 7593:   padding: 2px;
1.515     albertel 7594: }
1.523     albertel 7595: 
                   7596: .LC_answer_correct {
1.795     www      7597:   background: lightgreen;
                   7598:   color: darkgreen;
                   7599:   padding: 6px;
1.523     albertel 7600: }
1.795     www      7601: 
1.523     albertel 7602: .LC_answer_charged_try {
1.797     www      7603:   background: #FFAAAA;
1.795     www      7604:   color: darkred;
                   7605:   padding: 6px;
1.523     albertel 7606: }
1.795     www      7607: 
1.779     bisitz   7608: .LC_answer_not_charged_try,
1.523     albertel 7609: .LC_answer_no_grade,
                   7610: .LC_answer_late {
1.795     www      7611:   background: lightyellow;
1.523     albertel 7612:   color: black;
1.795     www      7613:   padding: 6px;
1.523     albertel 7614: }
1.795     www      7615: 
1.523     albertel 7616: .LC_answer_previous {
1.795     www      7617:   background: lightblue;
                   7618:   color: darkblue;
                   7619:   padding: 6px;
1.523     albertel 7620: }
1.795     www      7621: 
1.779     bisitz   7622: .LC_answer_no_message {
1.777     tempelho 7623:   background: #FFFFFF;
                   7624:   color: black;
1.795     www      7625:   padding: 6px;
1.779     bisitz   7626: }
1.795     www      7627: 
1.1334    raeburn  7628: .LC_answer_unknown,
                   7629: .LC_answer_warning {
1.779     bisitz   7630:   background: orange;
                   7631:   color: black;
1.795     www      7632:   padding: 6px;
1.777     tempelho 7633: }
1.795     www      7634: 
1.529     albertel 7635: span.LC_prior_numerical,
                   7636: span.LC_prior_string,
                   7637: span.LC_prior_custom,
                   7638: span.LC_prior_reaction,
                   7639: span.LC_prior_math {
1.925     bisitz   7640:   font-family: $mono;
1.523     albertel 7641:   white-space: pre;
                   7642: }
                   7643: 
1.525     albertel 7644: span.LC_prior_string {
1.925     bisitz   7645:   font-family: $mono;
1.525     albertel 7646:   white-space: pre;
                   7647: }
                   7648: 
1.523     albertel 7649: table.LC_prior_option {
                   7650:   width: 100%;
                   7651:   border-collapse: collapse;
                   7652: }
1.795     www      7653: 
1.911     bisitz   7654: table.LC_prior_rank,
1.795     www      7655: table.LC_prior_match {
1.528     albertel 7656:   border-collapse: collapse;
                   7657: }
1.795     www      7658: 
1.528     albertel 7659: table.LC_prior_option tr td,
                   7660: table.LC_prior_rank tr td,
                   7661: table.LC_prior_match tr td {
1.524     albertel 7662:   border: 1px solid #000000;
1.515     albertel 7663: }
                   7664: 
1.855     bisitz   7665: .LC_nobreak {
1.544     albertel 7666:   white-space: nowrap;
1.519     raeburn  7667: }
                   7668: 
1.576     raeburn  7669: span.LC_cusr_emph {
                   7670:   font-style: italic;
                   7671: }
                   7672: 
1.633     raeburn  7673: span.LC_cusr_subheading {
                   7674:   font-weight: normal;
                   7675:   font-size: 85%;
                   7676: }
                   7677: 
1.861     bisitz   7678: div.LC_docs_entry_move {
1.859     bisitz   7679:   border: 1px solid #BBBBBB;
1.545     albertel 7680:   background: #DDDDDD;
1.861     bisitz   7681:   width: 22px;
1.859     bisitz   7682:   padding: 1px;
                   7683:   margin: 0;
1.545     albertel 7684: }
                   7685: 
1.861     bisitz   7686: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7687: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7688:   font-size: x-small;
                   7689: }
1.795     www      7690: 
1.861     bisitz   7691: .LC_docs_entry_parameter {
                   7692:   white-space: nowrap;
                   7693: }
                   7694: 
1.544     albertel 7695: .LC_docs_copy {
1.545     albertel 7696:   color: #000099;
1.544     albertel 7697: }
1.795     www      7698: 
1.544     albertel 7699: .LC_docs_cut {
1.545     albertel 7700:   color: #550044;
1.544     albertel 7701: }
1.795     www      7702: 
1.544     albertel 7703: .LC_docs_rename {
1.545     albertel 7704:   color: #009900;
1.544     albertel 7705: }
1.795     www      7706: 
1.544     albertel 7707: .LC_docs_remove {
1.545     albertel 7708:   color: #990000;
                   7709: }
                   7710: 
1.1284    raeburn  7711: .LC_docs_alias {
                   7712:   color: #440055;  
                   7713: }
                   7714: 
1.1286    raeburn  7715: .LC_domprefs_email,
1.1284    raeburn  7716: .LC_docs_alias_name,
1.547     albertel 7717: .LC_docs_reinit_warn,
                   7718: .LC_docs_ext_edit {
                   7719:   font-size: x-small;
                   7720: }
                   7721: 
1.545     albertel 7722: table.LC_docs_adddocs td,
                   7723: table.LC_docs_adddocs th {
                   7724:   border: 1px solid #BBBBBB;
                   7725:   padding: 4px;
                   7726:   background: #DDDDDD;
1.543     albertel 7727: }
                   7728: 
1.584     albertel 7729: table.LC_sty_begin {
                   7730:   background: #BBFFBB;
                   7731: }
1.795     www      7732: 
1.584     albertel 7733: table.LC_sty_end {
                   7734:   background: #FFBBBB;
                   7735: }
                   7736: 
1.589     raeburn  7737: table.LC_double_column {
1.803     bisitz   7738:   border-width: 0;
1.589     raeburn  7739:   border-collapse: collapse;
                   7740:   width: 100%;
                   7741:   padding: 2px;
                   7742: }
                   7743: 
                   7744: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7745:   top: 2px;
1.589     raeburn  7746:   left: 2px;
                   7747:   width: 47%;
                   7748:   vertical-align: top;
                   7749: }
                   7750: 
                   7751: table.LC_double_column tr td.LC_right_col {
                   7752:   top: 2px;
1.779     bisitz   7753:   right: 2px;
1.589     raeburn  7754:   width: 47%;
                   7755:   vertical-align: top;
                   7756: }
                   7757: 
1.591     raeburn  7758: div.LC_left_float {
                   7759:   float: left;
                   7760:   padding-right: 5%;
1.597     albertel 7761:   padding-bottom: 4px;
1.591     raeburn  7762: }
                   7763: 
                   7764: div.LC_clear_float_header {
1.597     albertel 7765:   padding-bottom: 2px;
1.591     raeburn  7766: }
                   7767: 
                   7768: div.LC_clear_float_footer {
1.597     albertel 7769:   padding-top: 10px;
1.591     raeburn  7770:   clear: both;
                   7771: }
                   7772: 
1.597     albertel 7773: div.LC_grade_show_user {
1.941     bisitz   7774: /*  border-left: 5px solid $sidebg; */
                   7775:   border-top: 5px solid #000000;
                   7776:   margin: 50px 0 0 0;
1.936     bisitz   7777:   padding: 15px 0 5px 10px;
1.597     albertel 7778: }
1.795     www      7779: 
1.936     bisitz   7780: div.LC_grade_show_user_odd_row {
1.941     bisitz   7781: /*  border-left: 5px solid #000000; */
                   7782: }
                   7783: 
                   7784: div.LC_grade_show_user div.LC_Box {
                   7785:   margin-right: 50px;
1.597     albertel 7786: }
                   7787: 
                   7788: div.LC_grade_submissions,
                   7789: div.LC_grade_message_center,
1.936     bisitz   7790: div.LC_grade_info_links {
1.597     albertel 7791:   margin: 5px;
                   7792:   width: 99%;
                   7793:   background: #FFFFFF;
                   7794: }
1.795     www      7795: 
1.597     albertel 7796: div.LC_grade_submissions_header,
1.936     bisitz   7797: div.LC_grade_message_center_header {
1.705     tempelho 7798:   font-weight: bold;
                   7799:   font-size: large;
1.597     albertel 7800: }
1.795     www      7801: 
1.597     albertel 7802: div.LC_grade_submissions_body,
1.936     bisitz   7803: div.LC_grade_message_center_body {
1.597     albertel 7804:   border: 1px solid black;
                   7805:   width: 99%;
                   7806:   background: #FFFFFF;
                   7807: }
1.795     www      7808: 
1.613     albertel 7809: table.LC_scantron_action {
                   7810:   width: 100%;
                   7811: }
1.795     www      7812: 
1.613     albertel 7813: table.LC_scantron_action tr th {
1.698     harmsja  7814:   font-weight:bold;
                   7815:   font-style:normal;
1.613     albertel 7816: }
1.795     www      7817: 
1.779     bisitz   7818: .LC_edit_problem_header,
1.614     albertel 7819: div.LC_edit_problem_footer {
1.705     tempelho 7820:   font-weight: normal;
                   7821:   font-size:  medium;
1.602     albertel 7822:   margin: 2px;
1.1060    bisitz   7823:   background-color: $sidebg;
1.600     albertel 7824: }
1.795     www      7825: 
1.600     albertel 7826: div.LC_edit_problem_header,
1.602     albertel 7827: div.LC_edit_problem_header div,
1.614     albertel 7828: div.LC_edit_problem_footer,
                   7829: div.LC_edit_problem_footer div,
1.602     albertel 7830: div.LC_edit_problem_editxml_header,
                   7831: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7832:   z-index: 100;
1.600     albertel 7833: }
1.795     www      7834: 
1.600     albertel 7835: div.LC_edit_problem_header_title {
1.705     tempelho 7836:   font-weight: bold;
                   7837:   font-size: larger;
1.602     albertel 7838:   background: $tabbg;
                   7839:   padding: 3px;
1.1060    bisitz   7840:   margin: 0 0 5px 0;
1.602     albertel 7841: }
1.795     www      7842: 
1.602     albertel 7843: table.LC_edit_problem_header_title {
                   7844:   width: 100%;
1.600     albertel 7845:   background: $tabbg;
1.602     albertel 7846: }
                   7847: 
1.1205    golterma 7848: div.LC_edit_actionbar {
                   7849:     background-color: $sidebg;
1.1218    droeschl 7850:     margin: 0;
                   7851:     padding: 0;
                   7852:     line-height: 200%;
1.602     albertel 7853: }
1.795     www      7854: 
1.1218    droeschl 7855: div.LC_edit_actionbar div{
                   7856:     padding: 0;
                   7857:     margin: 0;
                   7858:     display: inline-block;
1.600     albertel 7859: }
1.795     www      7860: 
1.1124    bisitz   7861: .LC_edit_opt {
                   7862:   padding-left: 1em;
                   7863:   white-space: nowrap;
                   7864: }
                   7865: 
1.1152    golterma 7866: .LC_edit_problem_latexhelper{
                   7867:     text-align: right;
                   7868: }
                   7869: 
                   7870: #LC_edit_problem_colorful div{
                   7871:     margin-left: 40px;
                   7872: }
                   7873: 
1.1205    golterma 7874: #LC_edit_problem_codemirror div{
                   7875:     margin-left: 0px;
                   7876: }
                   7877: 
1.911     bisitz   7878: img.stift {
1.803     bisitz   7879:   border-width: 0;
                   7880:   vertical-align: middle;
1.677     riegler  7881: }
1.680     riegler  7882: 
1.923     bisitz   7883: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7884:   vertical-align: top;
1.777     tempelho 7885: }
1.795     www      7886: 
1.716     raeburn  7887: div.LC_createcourse {
1.911     bisitz   7888:   margin: 10px 10px 10px 10px;
1.716     raeburn  7889: }
                   7890: 
1.917     raeburn  7891: .LC_dccid {
1.1130    raeburn  7892:   float: right;
1.917     raeburn  7893:   margin: 0.2em 0 0 0;
                   7894:   padding: 0;
                   7895:   font-size: 90%;
                   7896:   display:none;
                   7897: }
                   7898: 
1.897     wenzelju 7899: ol.LC_primary_menu a:hover,
1.721     harmsja  7900: ol#LC_MenuBreadcrumbs a:hover,
                   7901: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7902: ul#LC_secondary_menu a:hover,
1.721     harmsja  7903: .LC_FormSectionClearButton input:hover
1.795     www      7904: ul.LC_TabContent   li:hover a {
1.952     onken    7905:   color:$button_hover;
1.911     bisitz   7906:   text-decoration:none;
1.693     droeschl 7907: }
                   7908: 
1.779     bisitz   7909: h1 {
1.911     bisitz   7910:   padding: 0;
                   7911:   line-height:130%;
1.693     droeschl 7912: }
1.698     harmsja  7913: 
1.911     bisitz   7914: h2,
                   7915: h3,
                   7916: h4,
                   7917: h5,
                   7918: h6 {
                   7919:   margin: 5px 0 5px 0;
                   7920:   padding: 0;
                   7921:   line-height:130%;
1.693     droeschl 7922: }
1.795     www      7923: 
                   7924: .LC_hcell {
1.911     bisitz   7925:   padding:3px 15px 3px 15px;
                   7926:   margin: 0;
                   7927:   background-color:$tabbg;
                   7928:   color:$fontmenu;
                   7929:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7930: }
1.795     www      7931: 
1.840     bisitz   7932: .LC_Box > .LC_hcell {
1.911     bisitz   7933:   margin: 0 -10px 10px -10px;
1.835     bisitz   7934: }
                   7935: 
1.721     harmsja  7936: .LC_noBorder {
1.911     bisitz   7937:   border: 0;
1.698     harmsja  7938: }
1.693     droeschl 7939: 
1.721     harmsja  7940: .LC_FormSectionClearButton input {
1.911     bisitz   7941:   background-color:transparent;
                   7942:   border: none;
                   7943:   cursor:pointer;
                   7944:   text-decoration:underline;
1.693     droeschl 7945: }
1.763     bisitz   7946: 
                   7947: .LC_help_open_topic {
1.911     bisitz   7948:   color: #FFFFFF;
                   7949:   background-color: #EEEEFF;
                   7950:   margin: 1px;
                   7951:   padding: 4px;
                   7952:   border: 1px solid #000033;
                   7953:   white-space: nowrap;
                   7954:   /* vertical-align: middle; */
1.759     neumanie 7955: }
1.693     droeschl 7956: 
1.911     bisitz   7957: dl,
                   7958: ul,
                   7959: div,
                   7960: fieldset {
                   7961:   margin: 10px 10px 10px 0;
                   7962:   /* overflow: hidden; */
1.693     droeschl 7963: }
1.795     www      7964: 
1.1211    raeburn  7965: article.geogebraweb div {
                   7966:     margin: 0;
                   7967: }
                   7968: 
1.838     bisitz   7969: fieldset > legend {
1.911     bisitz   7970:   font-weight: bold;
                   7971:   padding: 0 5px 0 5px;
1.838     bisitz   7972: }
                   7973: 
1.813     bisitz   7974: #LC_nav_bar {
1.911     bisitz   7975:   float: left;
1.995     raeburn  7976:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7977:   margin: 0 0 2px 0;
1.807     droeschl 7978: }
                   7979: 
1.916     droeschl 7980: #LC_realm {
                   7981:   margin: 0.2em 0 0 0;
                   7982:   padding: 0;
                   7983:   font-weight: bold;
                   7984:   text-align: center;
1.995     raeburn  7985:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7986: }
                   7987: 
1.911     bisitz   7988: #LC_nav_bar em {
                   7989:   font-weight: bold;
                   7990:   font-style: normal;
1.807     droeschl 7991: }
                   7992: 
1.897     wenzelju 7993: ol.LC_primary_menu {
1.934     droeschl 7994:   margin: 0;
1.1076    raeburn  7995:   padding: 0;
1.807     droeschl 7996: }
                   7997: 
1.852     droeschl 7998: ol#LC_PathBreadcrumbs {
1.911     bisitz   7999:   margin: 0;
1.693     droeschl 8000: }
                   8001: 
1.897     wenzelju 8002: ol.LC_primary_menu li {
1.1076    raeburn  8003:   color: RGB(80, 80, 80);
                   8004:   vertical-align: middle;
                   8005:   text-align: left;
                   8006:   list-style: none;
1.1205    golterma 8007:   position: relative;
1.1076    raeburn  8008:   float: left;
1.1205    golterma 8009:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8010:   line-height: 1.5em;
1.1076    raeburn  8011: }
                   8012: 
1.1205    golterma 8013: ol.LC_primary_menu li a,
                   8014: ol.LC_primary_menu li p {
1.1076    raeburn  8015:   display: block;
                   8016:   margin: 0;
                   8017:   padding: 0 5px 0 10px;
                   8018:   text-decoration: none;
                   8019: }
                   8020: 
1.1205    golterma 8021: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8022:   display: inline-block;
                   8023:   width: 95%;
                   8024:   text-align: left;
                   8025: }
                   8026: 
                   8027: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8028:   display: inline-block;	
                   8029:   width: 5%;
                   8030:   float: right;
                   8031:   text-align: right;
                   8032:   font-size: 70%;
                   8033: }
                   8034: 
                   8035: ol.LC_primary_menu ul {
1.1076    raeburn  8036:   display: none;
1.1205    golterma 8037:   width: 15em;
1.1076    raeburn  8038:   background-color: $data_table_light;
1.1205    golterma 8039:   position: absolute;
                   8040:   top: 100%;
1.1076    raeburn  8041: }
                   8042: 
1.1205    golterma 8043: ol.LC_primary_menu ul ul {
                   8044:   left: 100%;
                   8045:   top: 0;
                   8046: }
                   8047: 
                   8048: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8049:   display: block;
                   8050:   position: absolute;
                   8051:   margin: 0;
                   8052:   padding: 0;
1.1078    raeburn  8053:   z-index: 2;
1.1076    raeburn  8054: }
                   8055: 
                   8056: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8057: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8058:   font-size: 90%;
1.911     bisitz   8059:   vertical-align: top;
1.1076    raeburn  8060:   float: none;
1.1079    raeburn  8061:   border-left: 1px solid black;
                   8062:   border-right: 1px solid black;
1.1205    golterma 8063: /* A dark bottom border to visualize different menu options; 
                   8064: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8065:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8066: }
                   8067: 
1.1205    golterma 8068: ol.LC_primary_menu li li p:hover {
                   8069:   color:$button_hover;
                   8070:   text-decoration:none;
                   8071:   background-color:$data_table_dark;
1.1076    raeburn  8072: }
                   8073: 
                   8074: ol.LC_primary_menu li li a:hover {
                   8075:    color:$button_hover;
                   8076:    background-color:$data_table_dark;
1.693     droeschl 8077: }
                   8078: 
1.1205    golterma 8079: /* Font-size equal to the size of the predecessors*/
                   8080: ol.LC_primary_menu li:hover li li {
                   8081:   font-size: 100%;
                   8082: }
                   8083: 
1.897     wenzelju 8084: ol.LC_primary_menu li img {
1.911     bisitz   8085:   vertical-align: bottom;
1.934     droeschl 8086:   height: 1.1em;
1.1077    raeburn  8087:   margin: 0.2em 0 0 0;
1.693     droeschl 8088: }
                   8089: 
1.897     wenzelju 8090: ol.LC_primary_menu a {
1.911     bisitz   8091:   color: RGB(80, 80, 80);
                   8092:   text-decoration: none;
1.693     droeschl 8093: }
1.795     www      8094: 
1.949     droeschl 8095: ol.LC_primary_menu a.LC_new_message {
                   8096:   font-weight:bold;
                   8097:   color: darkred;
                   8098: }
                   8099: 
1.975     raeburn  8100: ol.LC_docs_parameters {
                   8101:   margin-left: 0;
                   8102:   padding: 0;
                   8103:   list-style: none;
                   8104: }
                   8105: 
                   8106: ol.LC_docs_parameters li {
                   8107:   margin: 0;
                   8108:   padding-right: 20px;
                   8109:   display: inline;
                   8110: }
                   8111: 
1.976     raeburn  8112: ol.LC_docs_parameters li:before {
                   8113:   content: "\\002022 \\0020";
                   8114: }
                   8115: 
                   8116: li.LC_docs_parameters_title {
                   8117:   font-weight: bold;
                   8118: }
                   8119: 
                   8120: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8121:   content: "";
                   8122: }
                   8123: 
1.897     wenzelju 8124: ul#LC_secondary_menu {
1.1107    raeburn  8125:   clear: right;
1.911     bisitz   8126:   color: $fontmenu;
                   8127:   background: $tabbg;
                   8128:   list-style: none;
                   8129:   padding: 0;
                   8130:   margin: 0;
                   8131:   width: 100%;
1.995     raeburn  8132:   text-align: left;
1.1107    raeburn  8133:   float: left;
1.808     droeschl 8134: }
                   8135: 
1.897     wenzelju 8136: ul#LC_secondary_menu li {
1.911     bisitz   8137:   font-weight: bold;
                   8138:   line-height: 1.8em;
1.1107    raeburn  8139:   border-right: 1px solid black;
                   8140:   float: left;
                   8141: }
                   8142: 
                   8143: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8144:   background-color: $data_table_light;
                   8145: }
                   8146: 
                   8147: ul#LC_secondary_menu li a {
1.911     bisitz   8148:   padding: 0 0.8em;
1.1107    raeburn  8149: }
                   8150: 
                   8151: ul#LC_secondary_menu li ul {
                   8152:   display: none;
                   8153: }
                   8154: 
                   8155: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8156:   display: block;
                   8157:   position: absolute;
                   8158:   margin: 0;
                   8159:   padding: 0;
                   8160:   list-style:none;
                   8161:   float: none;
                   8162:   background-color: $data_table_light;
                   8163:   z-index: 2;
                   8164:   margin-left: -1px;
                   8165: }
                   8166: 
                   8167: ul#LC_secondary_menu li ul li {
                   8168:   font-size: 90%;
                   8169:   vertical-align: top;
                   8170:   border-left: 1px solid black;
1.911     bisitz   8171:   border-right: 1px solid black;
1.1119    raeburn  8172:   background-color: $data_table_light;
1.1107    raeburn  8173:   list-style:none;
                   8174:   float: none;
                   8175: }
                   8176: 
                   8177: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8178:   background-color: $data_table_dark;
1.807     droeschl 8179: }
                   8180: 
1.847     tempelho 8181: ul.LC_TabContent {
1.911     bisitz   8182:   display:block;
                   8183:   background: $sidebg;
                   8184:   border-bottom: solid 1px $lg_border_color;
                   8185:   list-style:none;
1.1020    raeburn  8186:   margin: -1px -10px 0 -10px;
1.911     bisitz   8187:   padding: 0;
1.693     droeschl 8188: }
                   8189: 
1.795     www      8190: ul.LC_TabContent li,
                   8191: ul.LC_TabContentBigger li {
1.911     bisitz   8192:   float:left;
1.741     harmsja  8193: }
1.795     www      8194: 
1.897     wenzelju 8195: ul#LC_secondary_menu li a {
1.911     bisitz   8196:   color: $fontmenu;
                   8197:   text-decoration: none;
1.693     droeschl 8198: }
1.795     www      8199: 
1.721     harmsja  8200: ul.LC_TabContent {
1.952     onken    8201:   min-height:20px;
1.721     harmsja  8202: }
1.795     www      8203: 
                   8204: ul.LC_TabContent li {
1.911     bisitz   8205:   vertical-align:middle;
1.959     onken    8206:   padding: 0 16px 0 10px;
1.911     bisitz   8207:   background-color:$tabbg;
                   8208:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8209:   border-left: solid 1px $font;
1.721     harmsja  8210: }
1.795     www      8211: 
1.847     tempelho 8212: ul.LC_TabContent .right {
1.911     bisitz   8213:   float:right;
1.847     tempelho 8214: }
                   8215: 
1.911     bisitz   8216: ul.LC_TabContent li a,
                   8217: ul.LC_TabContent li {
                   8218:   color:rgb(47,47,47);
                   8219:   text-decoration:none;
                   8220:   font-size:95%;
                   8221:   font-weight:bold;
1.952     onken    8222:   min-height:20px;
                   8223: }
                   8224: 
1.959     onken    8225: ul.LC_TabContent li a:hover,
                   8226: ul.LC_TabContent li a:focus {
1.952     onken    8227:   color: $button_hover;
1.959     onken    8228:   background:none;
                   8229:   outline:none;
1.952     onken    8230: }
                   8231: 
                   8232: ul.LC_TabContent li:hover {
                   8233:   color: $button_hover;
                   8234:   cursor:pointer;
1.721     harmsja  8235: }
1.795     www      8236: 
1.911     bisitz   8237: ul.LC_TabContent li.active {
1.952     onken    8238:   color: $font;
1.911     bisitz   8239:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8240:   border-bottom:solid 1px #FFFFFF;
                   8241:   cursor: default;
1.744     ehlerst  8242: }
1.795     www      8243: 
1.959     onken    8244: ul.LC_TabContent li.active a {
                   8245:   color:$font;
                   8246:   background:#FFFFFF;
                   8247:   outline: none;
                   8248: }
1.1047    raeburn  8249: 
                   8250: ul.LC_TabContent li.goback {
                   8251:   float: left;
                   8252:   border-left: none;
                   8253: }
                   8254: 
1.870     tempelho 8255: #maincoursedoc {
1.911     bisitz   8256:   clear:both;
1.870     tempelho 8257: }
                   8258: 
                   8259: ul.LC_TabContentBigger {
1.911     bisitz   8260:   display:block;
                   8261:   list-style:none;
                   8262:   padding: 0;
1.870     tempelho 8263: }
                   8264: 
1.795     www      8265: ul.LC_TabContentBigger li {
1.911     bisitz   8266:   vertical-align:bottom;
                   8267:   height: 30px;
                   8268:   font-size:110%;
                   8269:   font-weight:bold;
                   8270:   color: #737373;
1.841     tempelho 8271: }
                   8272: 
1.957     onken    8273: ul.LC_TabContentBigger li.active {
                   8274:   position: relative;
                   8275:   top: 1px;
                   8276: }
                   8277: 
1.870     tempelho 8278: ul.LC_TabContentBigger li a {
1.911     bisitz   8279:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8280:   height: 30px;
                   8281:   line-height: 30px;
                   8282:   text-align: center;
                   8283:   display: block;
                   8284:   text-decoration: none;
1.958     onken    8285:   outline: none;  
1.741     harmsja  8286: }
1.795     www      8287: 
1.870     tempelho 8288: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8289:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8290:   color:$font;
1.744     ehlerst  8291: }
1.795     www      8292: 
1.870     tempelho 8293: ul.LC_TabContentBigger li b {
1.911     bisitz   8294:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8295:   display: block;
                   8296:   float: left;
                   8297:   padding: 0 30px;
1.957     onken    8298:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8299: }
                   8300: 
1.956     onken    8301: ul.LC_TabContentBigger li:hover b {
                   8302:   color:$button_hover;
                   8303: }
                   8304: 
1.870     tempelho 8305: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8306:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8307:   color:$font;
1.957     onken    8308:   border: 0;
1.741     harmsja  8309: }
1.693     droeschl 8310: 
1.870     tempelho 8311: 
1.862     bisitz   8312: ul.LC_CourseBreadcrumbs {
                   8313:   background: $sidebg;
1.1020    raeburn  8314:   height: 2em;
1.862     bisitz   8315:   padding-left: 10px;
1.1020    raeburn  8316:   margin: 0;
1.862     bisitz   8317:   list-style-position: inside;
                   8318: }
                   8319: 
1.911     bisitz   8320: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8321: ol#LC_PathBreadcrumbs {
1.911     bisitz   8322:   padding-left: 10px;
                   8323:   margin: 0;
1.933     droeschl 8324:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8325: }
                   8326: 
1.911     bisitz   8327: ol#LC_MenuBreadcrumbs li,
                   8328: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8329: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8330:   display: inline;
1.933     droeschl 8331:   white-space: normal;  
1.693     droeschl 8332: }
                   8333: 
1.823     bisitz   8334: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8335: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8336:   text-decoration: none;
                   8337:   font-size:90%;
1.693     droeschl 8338: }
1.795     www      8339: 
1.969     droeschl 8340: ol#LC_MenuBreadcrumbs h1 {
                   8341:   display: inline;
                   8342:   font-size: 90%;
                   8343:   line-height: 2.5em;
                   8344:   margin: 0;
                   8345:   padding: 0;
                   8346: }
                   8347: 
1.795     www      8348: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8349:   text-decoration:none;
                   8350:   font-size:100%;
                   8351:   font-weight:bold;
1.693     droeschl 8352: }
1.795     www      8353: 
1.840     bisitz   8354: .LC_Box {
1.911     bisitz   8355:   border: solid 1px $lg_border_color;
                   8356:   padding: 0 10px 10px 10px;
1.746     neumanie 8357: }
1.795     www      8358: 
1.1020    raeburn  8359: .LC_DocsBox {
                   8360:   border: solid 1px $lg_border_color;
                   8361:   padding: 0 0 10px 10px;
                   8362: }
                   8363: 
1.795     www      8364: .LC_AboutMe_Image {
1.911     bisitz   8365:   float:left;
                   8366:   margin-right:10px;
1.747     neumanie 8367: }
1.795     www      8368: 
                   8369: .LC_Clear_AboutMe_Image {
1.911     bisitz   8370:   clear:left;
1.747     neumanie 8371: }
1.795     www      8372: 
1.721     harmsja  8373: dl.LC_ListStyleClean dt {
1.911     bisitz   8374:   padding-right: 5px;
                   8375:   display: table-header-group;
1.693     droeschl 8376: }
                   8377: 
1.721     harmsja  8378: dl.LC_ListStyleClean dd {
1.911     bisitz   8379:   display: table-row;
1.693     droeschl 8380: }
                   8381: 
1.721     harmsja  8382: .LC_ListStyleClean,
                   8383: .LC_ListStyleSimple,
                   8384: .LC_ListStyleNormal,
1.795     www      8385: .LC_ListStyleSpecial {
1.911     bisitz   8386:   /* display:block; */
                   8387:   list-style-position: inside;
                   8388:   list-style-type: none;
                   8389:   overflow: hidden;
                   8390:   padding: 0;
1.693     droeschl 8391: }
                   8392: 
1.721     harmsja  8393: .LC_ListStyleSimple li,
                   8394: .LC_ListStyleSimple dd,
                   8395: .LC_ListStyleNormal li,
                   8396: .LC_ListStyleNormal dd,
                   8397: .LC_ListStyleSpecial li,
1.795     www      8398: .LC_ListStyleSpecial dd {
1.911     bisitz   8399:   margin: 0;
                   8400:   padding: 5px 5px 5px 10px;
                   8401:   clear: both;
1.693     droeschl 8402: }
                   8403: 
1.721     harmsja  8404: .LC_ListStyleClean li,
                   8405: .LC_ListStyleClean dd {
1.911     bisitz   8406:   padding-top: 0;
                   8407:   padding-bottom: 0;
1.693     droeschl 8408: }
                   8409: 
1.721     harmsja  8410: .LC_ListStyleSimple dd,
1.795     www      8411: .LC_ListStyleSimple li {
1.911     bisitz   8412:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8413: }
                   8414: 
1.721     harmsja  8415: .LC_ListStyleSpecial li,
                   8416: .LC_ListStyleSpecial dd {
1.911     bisitz   8417:   list-style-type: none;
                   8418:   background-color: RGB(220, 220, 220);
                   8419:   margin-bottom: 4px;
1.693     droeschl 8420: }
                   8421: 
1.721     harmsja  8422: table.LC_SimpleTable {
1.911     bisitz   8423:   margin:5px;
                   8424:   border:solid 1px $lg_border_color;
1.795     www      8425: }
1.693     droeschl 8426: 
1.721     harmsja  8427: table.LC_SimpleTable tr {
1.911     bisitz   8428:   padding: 0;
                   8429:   border:solid 1px $lg_border_color;
1.693     droeschl 8430: }
1.795     www      8431: 
                   8432: table.LC_SimpleTable thead {
1.911     bisitz   8433:   background:rgb(220,220,220);
1.693     droeschl 8434: }
                   8435: 
1.721     harmsja  8436: div.LC_columnSection {
1.911     bisitz   8437:   display: block;
                   8438:   clear: both;
                   8439:   overflow: hidden;
                   8440:   margin: 0;
1.693     droeschl 8441: }
                   8442: 
1.721     harmsja  8443: div.LC_columnSection>* {
1.911     bisitz   8444:   float: left;
                   8445:   margin: 10px 20px 10px 0;
                   8446:   overflow:hidden;
1.693     droeschl 8447: }
1.721     harmsja  8448: 
1.795     www      8449: table em {
1.911     bisitz   8450:   font-weight: bold;
                   8451:   font-style: normal;
1.748     schulted 8452: }
1.795     www      8453: 
1.779     bisitz   8454: table.LC_tableBrowseRes,
1.795     www      8455: table.LC_tableOfContent {
1.911     bisitz   8456:   border:none;
                   8457:   border-spacing: 1px;
                   8458:   padding: 3px;
                   8459:   background-color: #FFFFFF;
                   8460:   font-size: 90%;
1.753     droeschl 8461: }
1.789     droeschl 8462: 
1.911     bisitz   8463: table.LC_tableOfContent {
                   8464:   border-collapse: collapse;
1.789     droeschl 8465: }
                   8466: 
1.771     droeschl 8467: table.LC_tableBrowseRes a,
1.768     schulted 8468: table.LC_tableOfContent a {
1.911     bisitz   8469:   background-color: transparent;
                   8470:   text-decoration: none;
1.753     droeschl 8471: }
                   8472: 
1.795     www      8473: table.LC_tableOfContent img {
1.911     bisitz   8474:   border: none;
                   8475:   height: 1.3em;
                   8476:   vertical-align: text-bottom;
                   8477:   margin-right: 0.3em;
1.753     droeschl 8478: }
1.757     schulted 8479: 
1.795     www      8480: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8481:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8482: }
                   8483: 
1.795     www      8484: a#LC_content_toolbar_everything {
1.911     bisitz   8485:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8486: }
                   8487: 
1.795     www      8488: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8489:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8490: }
                   8491: 
1.795     www      8492: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8493:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8494: }
                   8495: 
1.795     www      8496: a#LC_content_toolbar_changefolder {
1.911     bisitz   8497:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8498: }
                   8499: 
1.795     www      8500: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8501:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8502: }
                   8503: 
1.1043    raeburn  8504: a#LC_content_toolbar_edittoplevel {
                   8505:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8506: }
                   8507: 
1.795     www      8508: ul#LC_toolbar li a:hover {
1.911     bisitz   8509:   background-position: bottom center;
1.757     schulted 8510: }
                   8511: 
1.795     www      8512: ul#LC_toolbar {
1.911     bisitz   8513:   padding: 0;
                   8514:   margin: 2px;
                   8515:   list-style:none;
                   8516:   position:relative;
                   8517:   background-color:white;
1.1082    raeburn  8518:   overflow: auto;
1.757     schulted 8519: }
                   8520: 
1.795     www      8521: ul#LC_toolbar li {
1.911     bisitz   8522:   border:1px solid white;
                   8523:   padding: 0;
                   8524:   margin: 0;
                   8525:   float: left;
                   8526:   display:inline;
                   8527:   vertical-align:middle;
1.1082    raeburn  8528:   white-space: nowrap;
1.911     bisitz   8529: }
1.757     schulted 8530: 
1.783     amueller 8531: 
1.795     www      8532: a.LC_toolbarItem {
1.911     bisitz   8533:   display:block;
                   8534:   padding: 0;
                   8535:   margin: 0;
                   8536:   height: 32px;
                   8537:   width: 32px;
                   8538:   color:white;
                   8539:   border: none;
                   8540:   background-repeat:no-repeat;
                   8541:   background-color:transparent;
1.757     schulted 8542: }
                   8543: 
1.915     droeschl 8544: ul.LC_funclist {
                   8545:     margin: 0;
                   8546:     padding: 0.5em 1em 0.5em 0;
                   8547: }
                   8548: 
1.933     droeschl 8549: ul.LC_funclist > li:first-child {
                   8550:     font-weight:bold; 
                   8551:     margin-left:0.8em;
                   8552: }
                   8553: 
1.915     droeschl 8554: ul.LC_funclist + ul.LC_funclist {
                   8555:     /* 
                   8556:        left border as a seperator if we have more than
                   8557:        one list 
                   8558:     */
                   8559:     border-left: 1px solid $sidebg;
                   8560:     /* 
                   8561:        this hides the left border behind the border of the 
                   8562:        outer box if element is wrapped to the next 'line' 
                   8563:     */
                   8564:     margin-left: -1px;
                   8565: }
                   8566: 
1.843     bisitz   8567: ul.LC_funclist li {
1.915     droeschl 8568:   display: inline;
1.782     bisitz   8569:   white-space: nowrap;
1.915     droeschl 8570:   margin: 0 0 0 25px;
                   8571:   line-height: 150%;
1.782     bisitz   8572: }
                   8573: 
1.974     wenzelju 8574: .LC_hidden {
                   8575:   display: none;
                   8576: }
                   8577: 
1.1030    www      8578: .LCmodal-overlay {
                   8579: 		position:fixed;
                   8580: 		top:0;
                   8581: 		right:0;
                   8582: 		bottom:0;
                   8583: 		left:0;
                   8584: 		height:100%;
                   8585: 		width:100%;
                   8586: 		margin:0;
                   8587: 		padding:0;
                   8588: 		background:#999;
                   8589: 		opacity:.75;
                   8590: 		filter: alpha(opacity=75);
                   8591: 		-moz-opacity: 0.75;
                   8592: 		z-index:101;
                   8593: }
                   8594: 
                   8595: * html .LCmodal-overlay {   
                   8596: 		position: absolute;
                   8597: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8598: }
                   8599: 
                   8600: .LCmodal-window {
                   8601: 		position:fixed;
                   8602: 		top:50%;
                   8603: 		left:50%;
                   8604: 		margin:0;
                   8605: 		padding:0;
                   8606: 		z-index:102;
                   8607: 	}
                   8608: 
                   8609: * html .LCmodal-window {
                   8610: 		position:absolute;
                   8611: }
                   8612: 
                   8613: .LCclose-window {
                   8614: 		position:absolute;
                   8615: 		width:32px;
                   8616: 		height:32px;
                   8617: 		right:8px;
                   8618: 		top:8px;
                   8619: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8620: 		text-indent:-99999px;
                   8621: 		overflow:hidden;
                   8622: 		cursor:pointer;
                   8623: }
                   8624: 
1.1369    raeburn  8625: .LCisDisabled {
                   8626:   cursor: not-allowed;
                   8627:   opacity: 0.5;
                   8628: }
                   8629: 
                   8630: a[aria-disabled="true"] {
                   8631:   color: currentColor;
                   8632:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8633:   pointer-events: none;
                   8634:   text-decoration: none;
                   8635: }
                   8636: 
1.1335    raeburn  8637: pre.LC_wordwrap {
                   8638:   white-space: pre-wrap;
                   8639:   white-space: -moz-pre-wrap;
                   8640:   white-space: -pre-wrap;
                   8641:   white-space: -o-pre-wrap;
                   8642:   word-wrap: break-word;
                   8643: }
                   8644: 
1.1100    raeburn  8645: /*
1.1231    damieng  8646:   styles used for response display
                   8647: */
                   8648: div.LC_radiofoil, div.LC_rankfoil {
                   8649:   margin: .5em 0em .5em 0em;
                   8650: }
                   8651: table.LC_itemgroup {
                   8652:   margin-top: 1em;
                   8653: }
                   8654: 
                   8655: /*
1.1100    raeburn  8656:   styles used by TTH when "Default set of options to pass to tth/m
                   8657:   when converting TeX" in course settings has been set
                   8658: 
                   8659:   option passed: -t
                   8660: 
                   8661: */
                   8662: 
                   8663: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8664: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8665: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8666: td div.norm {line-height:normal;}
                   8667: 
                   8668: /*
                   8669:   option passed -y3
                   8670: */
                   8671: 
                   8672: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8673: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8674: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8675: 
1.1230    damieng  8676: /*
                   8677:   sections with roles, for content only
                   8678: */
                   8679: section[class^="role-"] {
                   8680:   padding-left: 10px;
                   8681:   padding-right: 5px;
                   8682:   margin-top: 8px;
                   8683:   margin-bottom: 8px;
                   8684:   border: 1px solid #2A4;
                   8685:   border-radius: 5px;
                   8686:   box-shadow: 0px 1px 1px #BBB;
                   8687: }
                   8688: section[class^="role-"]>h1 {
                   8689:   position: relative;
                   8690:   margin: 0px;
                   8691:   padding-top: 10px;
                   8692:   padding-left: 40px;
                   8693: }
                   8694: section[class^="role-"]>h1:before {
                   8695:   position: absolute;
                   8696:   left: -5px;
                   8697:   top: 5px;
                   8698: }
                   8699: section.role-activity>h1:before {
                   8700:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8701: }
                   8702: section.role-advice>h1:before {
                   8703:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8704: }
                   8705: section.role-bibliography>h1:before {
                   8706:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8707: }
                   8708: section.role-citation>h1:before {
                   8709:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8710: }
                   8711: section.role-conclusion>h1:before {
                   8712:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8713: }
                   8714: section.role-definition>h1:before {
                   8715:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8716: }
                   8717: section.role-demonstration>h1:before {
                   8718:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8719: }
                   8720: section.role-example>h1:before {
                   8721:   content:url('/adm/daxe/images/section_icons/example.png');
                   8722: }
                   8723: section.role-explanation>h1:before {
                   8724:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8725: }
                   8726: section.role-introduction>h1:before {
                   8727:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8728: }
                   8729: section.role-method>h1:before {
                   8730:   content:url('/adm/daxe/images/section_icons/method.png');
                   8731: }
                   8732: section.role-more_information>h1:before {
                   8733:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8734: }
                   8735: section.role-objectives>h1:before {
                   8736:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8737: }
                   8738: section.role-prerequisites>h1:before {
                   8739:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8740: }
                   8741: section.role-remark>h1:before {
                   8742:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8743: }
                   8744: section.role-reminder>h1:before {
                   8745:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8746: }
                   8747: section.role-summary>h1:before {
                   8748:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8749: }
                   8750: section.role-syntax>h1:before {
                   8751:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8752: }
                   8753: section.role-warning>h1:before {
                   8754:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8755: }
                   8756: 
1.1269    raeburn  8757: #LC_minitab_header {
                   8758:   float:left;
                   8759:   width:100%;
                   8760:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8761:   font-size:93%;
                   8762:   line-height:normal;
                   8763:   margin: 0.5em 0 0.5em 0;
                   8764: }
                   8765: #LC_minitab_header ul {
                   8766:   margin:0;
                   8767:   padding:10px 10px 0;
                   8768:   list-style:none;
                   8769: }
                   8770: #LC_minitab_header li {
                   8771:   float:left;
                   8772:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8773:   margin:0;
                   8774:   padding:0 0 0 9px;
                   8775: }
                   8776: #LC_minitab_header a {
                   8777:   display:block;
                   8778:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8779:   padding:5px 15px 4px 6px;
                   8780: }
                   8781: #LC_minitab_header #LC_current_minitab {
                   8782:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8783: }
                   8784: #LC_minitab_header #LC_current_minitab a {
                   8785:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8786:   padding-bottom:5px;
                   8787: }
                   8788: 
                   8789: 
1.343     albertel 8790: END
                   8791: }
                   8792: 
1.306     albertel 8793: =pod
                   8794: 
                   8795: =item * &headtag()
                   8796: 
                   8797: Returns a uniform footer for LON-CAPA web pages.
                   8798: 
1.307     albertel 8799: Inputs: $title - optional title for the head
                   8800:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8801:         $args - optional arguments
1.319     albertel 8802:             force_register - if is true call registerurl so the remote is 
                   8803:                              informed
1.415     albertel 8804:             redirect       -> array ref of
                   8805:                                    1- seconds before redirect occurs
                   8806:                                    2- url to redirect to
                   8807:                                    3- whether the side effect should occur
1.315     albertel 8808:                            (side effect of setting 
                   8809:                                $env{'internal.head.redirect'} to the url 
                   8810:                                redirected too)
1.352     albertel 8811:             domain         -> force to color decorate a page for a specific
                   8812:                                domain
                   8813:             function       -> force usage of a specific rolish color scheme
                   8814:             bgcolor        -> override the default page bgcolor
1.460     albertel 8815:             no_auto_mt_title
                   8816:                            -> prevent &mt()ing the title arg
1.464     albertel 8817: 
1.306     albertel 8818: =cut
                   8819: 
                   8820: sub headtag {
1.313     albertel 8821:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8822:     
1.363     albertel 8823:     my $function = $args->{'function'} || &get_users_function();
                   8824:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8825:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8826:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8827:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8828: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8829: 		   #time(),
1.418     albertel 8830: 		   $env{'environment.color.timestamp'},
1.363     albertel 8831: 		   $function,$domain,$bgcolor);
                   8832: 
1.369     www      8833:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8834: 
1.308     albertel 8835:     my $result =
                   8836: 	'<head>'.
1.1160    raeburn  8837: 	&font_settings($args);
1.319     albertel 8838: 
1.1188    raeburn  8839:     my $inhibitprint;
                   8840:     if ($args->{'print_suppress'}) {
                   8841:         $inhibitprint = &print_suppression();
                   8842:     }
1.1064    raeburn  8843: 
1.461     albertel 8844:     if (!$args->{'frameset'}) {
                   8845: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8846:     }
1.962     droeschl 8847:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8848:         $result .= Apache::lonxml::display_title();
1.319     albertel 8849:     }
1.436     albertel 8850:     if (!$args->{'no_nav_bar'} 
                   8851: 	&& !$args->{'only_body'}
                   8852: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8853: 	$result .= &help_menu_js($httphost);
1.1032    www      8854:         $result.=&modal_window();
1.1038    www      8855:         $result.=&togglebox_script();
1.1034    www      8856:         $result.=&wishlist_window();
1.1041    www      8857:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8858:     } else {
                   8859:         if ($args->{'add_modal'}) {
                   8860:            $result.=&modal_window();
                   8861:         }
                   8862:         if ($args->{'add_wishlist'}) {
                   8863:            $result.=&wishlist_window();
                   8864:         }
1.1038    www      8865:         if ($args->{'add_togglebox'}) {
                   8866:            $result.=&togglebox_script();
                   8867:         }
1.1041    www      8868:         if ($args->{'add_progressbar'}) {
                   8869:            $result.=&LCprogressbarUpdate_script();
                   8870:         }
1.436     albertel 8871:     }
1.314     albertel 8872:     if (ref($args->{'redirect'})) {
1.414     albertel 8873: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8874: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8875: 	if (!$inhibit_continue) {
                   8876: 	    $env{'internal.head.redirect'} = $url;
                   8877: 	}
1.313     albertel 8878: 	$result.=<<ADDMETA
                   8879: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8880: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8881: ADDMETA
1.1210    raeburn  8882:     } else {
                   8883:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8884:             my $requrl = $env{'request.uri'};
                   8885:             if ($requrl eq '') {
                   8886:                 $requrl = $ENV{'REQUEST_URI'};
                   8887:                 $requrl =~ s/\?.+$//;
                   8888:             }
                   8889:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8890:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8891:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8892:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8893:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8894:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8895:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  8896:                     my ($offload,$offloadoth);
1.1210    raeburn  8897:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8898:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8899:                             $offload = 1;
1.1353    raeburn  8900:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8901:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8902:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8903:                                     $offloadoth = 1;
                   8904:                                     $dom_in_use = $env{'user.domain'};
                   8905:                                 }
                   8906:                             }
1.1340    raeburn  8907:                         }
                   8908:                     }
                   8909:                     unless ($offload) {
                   8910:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8911:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8912:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8913:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8914:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8915:                                         $offload = 1;
1.1352    raeburn  8916:                                         $offloadoth = 1;
1.1340    raeburn  8917:                                         $dom_in_use = $env{'user.domain'};
                   8918:                                     }
1.1210    raeburn  8919:                                 }
1.1340    raeburn  8920:                             }
                   8921:                         }
                   8922:                     }
                   8923:                     if ($offload) {
1.1358    raeburn  8924:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  8925:                         if (($newserver eq '') && ($offloadoth)) {
                   8926:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8927:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8928:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8929:                             }
                   8930:                         }
1.1340    raeburn  8931:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8932:                             my $numsec = 5;
                   8933:                             my $timeout = $numsec * 1000;
                   8934:                             my ($newurl,$locknum,%locks,$msg);
                   8935:                             if ($env{'request.role.adv'}) {
                   8936:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8937:                             }
                   8938:                             my $disable_submit = 0;
                   8939:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8940:                                 $disable_submit = 1;
                   8941:                             }
                   8942:                             if ($locknum) {
                   8943:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  8944:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  8945:                                        join(", ",sort(values(%locks)))."\n";
                   8946:                                 if (&show_course()) {
                   8947:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8948:                                 } else {
                   8949:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8950:                                 }
1.1340    raeburn  8951:                             } else {
                   8952:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8953:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8954:                                 }
                   8955:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8956:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8957:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8958:                                     $newurl .= '&role='.$env{'request.role'};
                   8959:                                 }
                   8960:                                 if ($env{'request.symb'}) {
                   8961:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8962:                                     if ($shownsymb =~ m{^/enc/}) {
                   8963:                                         my $reqdmajor = 2;
                   8964:                                         my $reqdminor = 11;
                   8965:                                         my $reqdsubminor = 3;
                   8966:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8967:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8968:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8969:                                         if (($major eq '' && $minor eq '') ||
                   8970:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8971:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8972:                                              ($reqdsubminor > $subminor))))) {
                   8973:                                             undef($shownsymb);
                   8974:                                         }
1.1210    raeburn  8975:                                     }
1.1340    raeburn  8976:                                     if ($shownsymb) {
                   8977:                                         &js_escape(\$shownsymb);
                   8978:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  8979:                                     }
1.1340    raeburn  8980:                                 } else {
                   8981:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8982:                                     &js_escape(\$shownurl);
                   8983:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  8984:                                 }
1.1340    raeburn  8985:                             }
                   8986:                             &js_escape(\$msg);
                   8987:                             $result.=<<OFFLOAD
1.1210    raeburn  8988: <meta http-equiv="pragma" content="no-cache" />
                   8989: <script type="text/javascript">
1.1215    raeburn  8990: // <![CDATA[
1.1210    raeburn  8991: function LC_Offload_Now() {
                   8992:     var dest = "$newurl";
                   8993:     if (dest != '') {
                   8994:         window.location.href="$newurl";
                   8995:     }
                   8996: }
1.1214    raeburn  8997: \$(document).ready(function () {
                   8998:     window.alert('$msg');
                   8999:     if ($disable_submit) {
1.1210    raeburn  9000:         \$(".LC_hwk_submit").prop("disabled", true);
                   9001:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9002:     }
                   9003:     setTimeout('LC_Offload_Now()', $timeout);
                   9004: });
1.1215    raeburn  9005: // ]]>
1.1210    raeburn  9006: </script>
                   9007: OFFLOAD
                   9008:                         }
                   9009:                     }
                   9010:                 }
                   9011:             }
                   9012:         }
1.313     albertel 9013:     }
1.306     albertel 9014:     if (!defined($title)) {
                   9015: 	$title = 'The LearningOnline Network with CAPA';
                   9016:     }
1.460     albertel 9017:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9018:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9019: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9020:     if (!$args->{'frameset'}) {
                   9021:         $result .= ' /';
                   9022:     }
                   9023:     $result .= '>' 
1.1064    raeburn  9024:         .$inhibitprint
1.414     albertel 9025: 	.$head_extra;
1.1242    raeburn  9026:     my $clientmobile;
                   9027:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9028:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9029:     } else {
                   9030:         $clientmobile = $env{'browser.mobile'};
                   9031:     }
                   9032:     if ($clientmobile) {
1.1137    raeburn  9033:         $result .= '
                   9034: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9035: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9036:     }
1.1278    raeburn  9037:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9038:     return $result.'</head>';
1.306     albertel 9039: }
                   9040: 
                   9041: =pod
                   9042: 
1.340     albertel 9043: =item * &font_settings()
                   9044: 
                   9045: Returns neccessary <meta> to set the proper encoding
                   9046: 
1.1160    raeburn  9047: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9048: 
                   9049: =cut
                   9050: 
                   9051: sub font_settings {
1.1160    raeburn  9052:     my ($args) = @_;
1.340     albertel 9053:     my $headerstring='';
1.1160    raeburn  9054:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9055:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9056:         $headerstring.=
                   9057:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9058:         if (!$args->{'frameset'}) {
                   9059: 	    $headerstring.= ' /';
                   9060:         }
                   9061: 	$headerstring .= '>'."\n";
1.340     albertel 9062:     }
                   9063:     return $headerstring;
                   9064: }
                   9065: 
1.341     albertel 9066: =pod
                   9067: 
1.1064    raeburn  9068: =item * &print_suppression()
                   9069: 
                   9070: In course context returns css which causes the body to be blank when media="print",
                   9071: if printout generation is unavailable for the current resource.
                   9072: 
                   9073: This could be because:
                   9074: 
                   9075: (a) printstartdate is in the future
                   9076: 
                   9077: (b) printenddate is in the past
                   9078: 
                   9079: (c) there is an active exam block with "printout"
                   9080: functionality blocked
                   9081: 
                   9082: Users with pav, pfo or evb privileges are exempt.
                   9083: 
                   9084: Inputs: none
                   9085: 
                   9086: =cut
                   9087: 
                   9088: 
                   9089: sub print_suppression {
                   9090:     my $noprint;
                   9091:     if ($env{'request.course.id'}) {
                   9092:         my $scope = $env{'request.course.id'};
                   9093:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9094:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9095:             return;
                   9096:         }
                   9097:         if ($env{'request.course.sec'} ne '') {
                   9098:             $scope .= "/$env{'request.course.sec'}";
                   9099:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9100:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9101:                 return;
1.1064    raeburn  9102:             }
                   9103:         }
                   9104:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9105:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9106:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9107:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9108:         if ($blocked) {
                   9109:             my $checkrole = "cm./$cdom/$cnum";
                   9110:             if ($env{'request.course.sec'} ne '') {
                   9111:                 $checkrole .= "/$env{'request.course.sec'}";
                   9112:             }
                   9113:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9114:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9115:                 $noprint = 1;
                   9116:             }
                   9117:         }
                   9118:         unless ($noprint) {
                   9119:             my $symb = &Apache::lonnet::symbread();
                   9120:             if ($symb ne '') {
                   9121:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9122:                 if (ref($navmap)) {
                   9123:                     my $res = $navmap->getBySymb($symb);
                   9124:                     if (ref($res)) {
                   9125:                         if (!$res->resprintable()) {
                   9126:                             $noprint = 1;
                   9127:                         }
                   9128:                     }
                   9129:                 }
                   9130:             }
                   9131:         }
                   9132:         if ($noprint) {
                   9133:             return <<"ENDSTYLE";
                   9134: <style type="text/css" media="print">
                   9135:     body { display:none }
                   9136: </style>
                   9137: ENDSTYLE
                   9138:         }
                   9139:     }
                   9140:     return;
                   9141: }
                   9142: 
                   9143: =pod
                   9144: 
1.341     albertel 9145: =item * &xml_begin()
                   9146: 
                   9147: Returns the needed doctype and <html>
                   9148: 
                   9149: Inputs: none
                   9150: 
                   9151: =cut
                   9152: 
                   9153: sub xml_begin {
1.1168    raeburn  9154:     my ($is_frameset) = @_;
1.341     albertel 9155:     my $output='';
                   9156: 
                   9157:     if ($env{'browser.mathml'}) {
                   9158: 	$output='<?xml version="1.0"?>'
                   9159:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9160: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9161:             
                   9162: #	    .'<!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">] >'
                   9163: 	    .'<!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">'
                   9164:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9165: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9166:     } elsif ($is_frameset) {
                   9167:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9168:                 '<html>'."\n";
1.341     albertel 9169:     } else {
1.1168    raeburn  9170: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9171:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9172:     }
                   9173:     return $output;
                   9174: }
1.340     albertel 9175: 
                   9176: =pod
                   9177: 
1.306     albertel 9178: =item * &start_page()
                   9179: 
                   9180: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9181: 
1.648     raeburn  9182: Inputs:
                   9183: 
                   9184: =over 4
                   9185: 
                   9186: $title - optional title for the page
                   9187: 
                   9188: $head_extra - optional extra HTML to incude inside the <head>
                   9189: 
                   9190: $args - additional optional args supported are:
                   9191: 
                   9192: =over 8
                   9193: 
                   9194:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9195:                                     arg on
1.814     bisitz   9196:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9197:              add_entries    -> additional attributes to add to the  <body>
                   9198:              domain         -> force to color decorate a page for a 
1.317     albertel 9199:                                     specific domain
1.648     raeburn  9200:              function       -> force usage of a specific rolish color
1.317     albertel 9201:                                     scheme
1.648     raeburn  9202:              redirect       -> see &headtag()
                   9203:              bgcolor        -> override the default page bg color
                   9204:              js_ready       -> return a string ready for being used in 
1.317     albertel 9205:                                     a javascript writeln
1.648     raeburn  9206:              html_encode    -> return a string ready for being used in 
1.320     albertel 9207:                                     a html attribute
1.648     raeburn  9208:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9209:                                     $forcereg arg
1.648     raeburn  9210:              frameset       -> if true will start with a <frameset>
1.330     albertel 9211:                                     rather than <body>
1.648     raeburn  9212:              skip_phases    -> hash ref of 
1.338     albertel 9213:                                     head -> skip the <html><head> generation
                   9214:                                     body -> skip all <body> generation
1.648     raeburn  9215:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9216:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9217:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9218:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9219:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9220:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9221:                                specific group
                   9222:              use_absolute   -> for request for external resource or syllabus, this
                   9223:                                will contain https://<hostname> if server uses
                   9224:                                https (as per hosts.tab), but request is for http
                   9225:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9226:              links_disabled -> Links in primary and secondary menus are disabled
                   9227:                                (Can enable them once page has loaded - see lonroles.pm
                   9228:                                for an example).
1.361     albertel 9229: 
1.648     raeburn  9230: =back
1.460     albertel 9231: 
1.648     raeburn  9232: =back
1.562     albertel 9233: 
1.306     albertel 9234: =cut
                   9235: 
                   9236: sub start_page {
1.309     albertel 9237:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9238:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9239: 
1.315     albertel 9240:     $env{'internal.start_page'}++;
1.1359    raeburn  9241:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9242: 
1.338     albertel 9243:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9244:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9245:     }
1.1316    raeburn  9246: 
                   9247:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9248:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9249:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9250:                 $args->{'no_primary_menu'} = 1;
                   9251:             }
                   9252:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9253:                 $args->{'no_inline_menu'} = 1;
                   9254:             }
                   9255:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9256:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9257:             }
                   9258:         } else {
                   9259:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9260:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9261:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9262:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9263:                     $args->{'no_primary_menu'} = 1;
                   9264:                 }
                   9265:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9266:                     $args->{'no_inline_menu'} = 1;
                   9267:                 }
                   9268:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9269:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9270:                 }
                   9271:             }
                   9272:         }
1.1316    raeburn  9273:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9274:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9275:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9276:     } elsif ($env{'request.course.id'}) {
                   9277:         my $expiretime=600;
                   9278:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9279:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9280:         }
                   9281:         my ($deeplinkmenu,$menuref);
                   9282:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9283:         if ($menucoll) {
                   9284:             if (ref($menuref) eq 'HASH') {
                   9285:                 %menu = %{$menuref};
                   9286:             }
                   9287:             if ($menu{'top'} eq 'n') {
                   9288:                 $args->{'no_primary_menu'} = 1;
                   9289:             }
                   9290:             if ($menu{'inline'} eq 'n') {
                   9291:                 unless (&Apache::lonnet::allowed('opa')) {
                   9292:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9293:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9294:                     my $crstype = &course_type();
                   9295:                     my $now = time;
                   9296:                     my $ccrole;
                   9297:                     if ($crstype eq 'Community') {
                   9298:                         $ccrole = 'co';
                   9299:                     } else {
                   9300:                         $ccrole = 'cc';
                   9301:                     }
                   9302:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9303:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9304:                         if ((($start) && ($start<0)) ||
                   9305:                             (($end) && ($end<$now))  ||
                   9306:                             (($start) && ($now<$start))) {
                   9307:                             $args->{'no_inline_menu'} = 1;
                   9308:                         }
                   9309:                     } else {
                   9310:                         $args->{'no_inline_menu'} = 1;
                   9311:                     }
                   9312:                 }
                   9313:             }
                   9314:         }
1.1316    raeburn  9315:     }
1.1359    raeburn  9316: 
1.338     albertel 9317:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9318: 	if ($args->{'frameset'}) {
                   9319: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9320: 						$args->{'add_entries'});
                   9321: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9322:         } else {
                   9323:             $result .=
                   9324:                 &bodytag($title, 
                   9325:                          $args->{'function'},       $args->{'add_entries'},
                   9326:                          $args->{'only_body'},      $args->{'domain'},
                   9327:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9328:                          $args->{'bgcolor'},        $args,
1.1359    raeburn  9329:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
1.831     bisitz   9330:         }
1.330     albertel 9331:     }
1.338     albertel 9332: 
1.315     albertel 9333:     if ($args->{'js_ready'}) {
1.713     kaisler  9334: 		$result = &js_ready($result);
1.315     albertel 9335:     }
1.320     albertel 9336:     if ($args->{'html_encode'}) {
1.713     kaisler  9337: 		$result = &html_encode($result);
                   9338:     }
                   9339: 
1.813     bisitz   9340:     # Preparation for new and consistent functionlist at top of screen
                   9341:     # if ($args->{'functionlist'}) {
                   9342:     #            $result .= &build_functionlist();
                   9343:     #}
                   9344: 
1.964     droeschl 9345:     # Don't add anything more if only_body wanted or in const space
                   9346:     return $result if    $args->{'only_body'} 
                   9347:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9348: 
                   9349:     #Breadcrumbs
1.758     kaisler  9350:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   9351: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9352: 		#if any br links exists, add them to the breadcrumbs
                   9353: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9354: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9355: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9356: 			}
                   9357: 		}
1.1096    raeburn  9358:                 # if @advtools array contains items add then to the breadcrumbs
                   9359:                 if (@advtools > 0) {
                   9360:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9361:                 }
1.1272    raeburn  9362:                 my $menulink;
                   9363:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9364:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9365:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9366:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9367:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9368:                      (!$env{'request.role.adv'}))) {
                   9369:                     $menulink = 0;
                   9370:                 } else {
                   9371:                     undef($menulink);
                   9372:                 }
1.758     kaisler  9373: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9374: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9375: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9376:                 } else {
1.1272    raeburn  9377: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9378: 		}
1.320     albertel 9379:     }
1.315     albertel 9380:     return $result;
1.306     albertel 9381: }
                   9382: 
                   9383: sub end_page {
1.315     albertel 9384:     my ($args) = @_;
                   9385:     $env{'internal.end_page'}++;
1.330     albertel 9386:     my $result;
1.335     albertel 9387:     if ($args->{'discussion'}) {
                   9388: 	my ($target,$parser);
                   9389: 	if (ref($args->{'discussion'})) {
                   9390: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9391: 				$args->{'discussion'}{'parser'});
                   9392: 	}
                   9393: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9394:     }
1.330     albertel 9395:     if ($args->{'frameset'}) {
                   9396: 	$result .= '</frameset>';
                   9397:     } else {
1.635     raeburn  9398: 	$result .= &endbodytag($args);
1.330     albertel 9399:     }
1.1080    raeburn  9400:     unless ($args->{'notbody'}) {
                   9401:         $result .= "\n</html>";
                   9402:     }
1.330     albertel 9403: 
1.315     albertel 9404:     if ($args->{'js_ready'}) {
1.317     albertel 9405: 	$result = &js_ready($result);
1.315     albertel 9406:     }
1.335     albertel 9407: 
1.320     albertel 9408:     if ($args->{'html_encode'}) {
                   9409: 	$result = &html_encode($result);
                   9410:     }
1.335     albertel 9411: 
1.315     albertel 9412:     return $result;
                   9413: }
                   9414: 
1.1359    raeburn  9415: sub menucoll_in_effect {
                   9416:     my ($menucoll,$deeplinkmenu,%menu);
                   9417:     if ($env{'request.course.id'}) {
                   9418:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9419:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9420:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9421:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9422:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9423:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9424:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9425:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9426:                     if (ref($navmap)) {
                   9427:                         $deeplink = $navmap->get_mapparam(undef,
                   9428:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9429:                                                           '0.deeplink');
1.1370    raeburn  9430:                     } else {
                   9431:                         $check_login_symb = 1;
1.1362    raeburn  9432:                     }
                   9433:                 } else {
1.1370    raeburn  9434:                     my $symb = &Apache::lonnet::symbread();
                   9435:                     if ($symb) {
                   9436:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9437:                     } else {
                   9438:                         $check_login_symb = 1;
                   9439:                     }
1.1362    raeburn  9440:                 }
                   9441:             } else {
1.1370    raeburn  9442:                 $check_login_symb = 1;
                   9443:             }
                   9444:             if ($check_login_symb) {
1.1362    raeburn  9445:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9446:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9447:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9448:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9449:                     if (ref($navmap)) {
                   9450:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9451:                     }
                   9452:                 } else {
                   9453:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9454:                 }
                   9455:             }
1.1359    raeburn  9456:             if ($deeplink ne '') {
1.1363    raeburn  9457:                 my ($state,$others,$listed,$scope,$protect,$display) = split(/,/,$deeplink);
1.1359    raeburn  9458:                 if ($display =~ /^\d+$/) {
                   9459:                     $deeplinkmenu = 1;
                   9460:                     $menucoll = $display;
                   9461:                 }
                   9462:             }
                   9463:         }
                   9464:         if ($menucoll) {
                   9465:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9466:         }
                   9467:     }
                   9468:     return ($menucoll,$deeplinkmenu,\%menu);
                   9469: }
                   9470: 
1.1362    raeburn  9471: sub deeplink_login_symb {
                   9472:     my ($cnum,$cdom) = @_;
                   9473:     my $login_symb;
                   9474:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9475:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9476:     }
                   9477:     return $login_symb;
                   9478: }
                   9479: 
                   9480: sub symb_from_tinyurl {
                   9481:     my ($url,$cnum,$cdom) = @_;
                   9482:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9483:         my $key = $1;
                   9484:         my ($tinyurl,$login);
                   9485:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9486:         if (defined($cached)) {
                   9487:             $tinyurl = $result;
                   9488:         } else {
                   9489:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9490:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9491:             if ($currtiny{$key} ne '') {
                   9492:                 $tinyurl = $currtiny{$key};
                   9493:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9494:             }
1.1364    raeburn  9495:         }
                   9496:         if ($tinyurl ne '') {
                   9497:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9498:             if (wantarray) {
                   9499:                 return ($cnumreq,$symb);
                   9500:             } elsif ($cnumreq eq $cnum) {
                   9501:                 return $symb;
1.1362    raeburn  9502:             }
                   9503:         }
                   9504:     }
1.1364    raeburn  9505:     if (wantarray) {
                   9506:         return ();
                   9507:     } else {
                   9508:         return;
                   9509:     }
1.1362    raeburn  9510: }
                   9511: 
1.1034    www      9512: sub wishlist_window {
                   9513:     return(<<'ENDWISHLIST');
1.1046    raeburn  9514: <script type="text/javascript">
1.1034    www      9515: // <![CDATA[
                   9516: // <!-- BEGIN LON-CAPA Internal
                   9517: function set_wishlistlink(title, path) {
                   9518:     if (!title) {
                   9519:         title = document.title;
                   9520:         title = title.replace(/^LON-CAPA /,'');
                   9521:     }
1.1175    raeburn  9522:     title = encodeURIComponent(title);
1.1203    raeburn  9523:     title = title.replace("'","\\\'");
1.1034    www      9524:     if (!path) {
                   9525:         path = location.pathname;
                   9526:     }
1.1175    raeburn  9527:     path = encodeURIComponent(path);
1.1203    raeburn  9528:     path = path.replace("'","\\\'");
1.1034    www      9529:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9530:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9531: }
                   9532: // END LON-CAPA Internal -->
                   9533: // ]]>
                   9534: </script>
                   9535: ENDWISHLIST
                   9536: }
                   9537: 
1.1030    www      9538: sub modal_window {
                   9539:     return(<<'ENDMODAL');
1.1046    raeburn  9540: <script type="text/javascript">
1.1030    www      9541: // <![CDATA[
                   9542: // <!-- BEGIN LON-CAPA Internal
                   9543: var modalWindow = {
                   9544: 	parent:"body",
                   9545: 	windowId:null,
                   9546: 	content:null,
                   9547: 	width:null,
                   9548: 	height:null,
                   9549: 	close:function()
                   9550: 	{
                   9551: 	        $(".LCmodal-window").remove();
                   9552: 	        $(".LCmodal-overlay").remove();
                   9553: 	},
                   9554: 	open:function()
                   9555: 	{
                   9556: 		var modal = "";
                   9557: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9558: 		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;\">";
                   9559: 		modal += this.content;
                   9560: 		modal += "</div>";	
                   9561: 
                   9562: 		$(this.parent).append(modal);
                   9563: 
                   9564: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9565: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9566: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9567: 	}
                   9568: };
1.1140    raeburn  9569: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9570: 	{
1.1266    raeburn  9571:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9572: 		modalWindow.windowId = "myModal";
                   9573: 		modalWindow.width = width;
                   9574: 		modalWindow.height = height;
1.1196    raeburn  9575: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9576: 		modalWindow.open();
1.1208    raeburn  9577: 	};
1.1030    www      9578: // END LON-CAPA Internal -->
                   9579: // ]]>
                   9580: </script>
                   9581: ENDMODAL
                   9582: }
                   9583: 
                   9584: sub modal_link {
1.1140    raeburn  9585:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9586:     unless ($width) { $width=480; }
                   9587:     unless ($height) { $height=400; }
1.1031    www      9588:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9589:     unless ($transparency) { $transparency='true'; }
                   9590: 
1.1074    raeburn  9591:     my $target_attr;
                   9592:     if (defined($target)) {
                   9593:         $target_attr = 'target="'.$target.'"';
                   9594:     }
                   9595:     return <<"ENDLINK";
1.1336    raeburn  9596: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9597: ENDLINK
1.1030    www      9598: }
                   9599: 
1.1032    www      9600: sub modal_adhoc_script {
1.1365    raeburn  9601:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9602:     my $mathjax;
                   9603:     if ($possmathjax) {
                   9604:         $mathjax = <<'ENDJAX';
                   9605:                if (typeof MathJax == 'object') {
                   9606:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9607:                }
                   9608: ENDJAX
                   9609:     }
1.1032    www      9610:     return (<<ENDADHOC);
1.1046    raeburn  9611: <script type="text/javascript">
1.1032    www      9612: // <![CDATA[
                   9613:         var $funcname = function()
                   9614:         {
                   9615:                 modalWindow.windowId = "myModal";
                   9616:                 modalWindow.width = $width;
                   9617:                 modalWindow.height = $height;
                   9618:                 modalWindow.content = '$content';
                   9619:                 modalWindow.open();
1.1365    raeburn  9620:                 $mathjax
1.1032    www      9621:         };  
                   9622: // ]]>
                   9623: </script>
                   9624: ENDADHOC
                   9625: }
                   9626: 
1.1041    www      9627: sub modal_adhoc_inner {
1.1365    raeburn  9628:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9629:     my $innerwidth=$width-20;
                   9630:     $content=&js_ready(
1.1140    raeburn  9631:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9632:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9633:                  $content.
1.1041    www      9634:                  &end_scrollbox().
1.1140    raeburn  9635:                  &end_page()
1.1041    www      9636:              );
1.1365    raeburn  9637:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9638: }
                   9639: 
                   9640: sub modal_adhoc_window {
1.1365    raeburn  9641:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9642:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9643:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9644: }
                   9645: 
                   9646: sub modal_adhoc_launch {
                   9647:     my ($funcname,$width,$height,$content)=@_;
                   9648:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9649: <script type="text/javascript">
                   9650: // <![CDATA[
                   9651: $funcname();
                   9652: // ]]>
                   9653: </script>
                   9654: ENDLAUNCH
                   9655: }
                   9656: 
                   9657: sub modal_adhoc_close {
                   9658:     return (<<ENDCLOSE);
                   9659: <script type="text/javascript">
                   9660: // <![CDATA[
                   9661: modalWindow.close();
                   9662: // ]]>
                   9663: </script>
                   9664: ENDCLOSE
                   9665: }
                   9666: 
1.1038    www      9667: sub togglebox_script {
                   9668:    return(<<ENDTOGGLE);
                   9669: <script type="text/javascript"> 
                   9670: // <![CDATA[
                   9671: function LCtoggleDisplay(id,hidetext,showtext) {
                   9672:    link = document.getElementById(id + "link").childNodes[0];
                   9673:    with (document.getElementById(id).style) {
                   9674:       if (display == "none" ) {
                   9675:           display = "inline";
                   9676:           link.nodeValue = hidetext;
                   9677:         } else {
                   9678:           display = "none";
                   9679:           link.nodeValue = showtext;
                   9680:        }
                   9681:    }
                   9682: }
                   9683: // ]]>
                   9684: </script>
                   9685: ENDTOGGLE
                   9686: }
                   9687: 
1.1039    www      9688: sub start_togglebox {
                   9689:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9690:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9691:     unless ($showtext) { $showtext=&mt('show'); }
                   9692:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9693:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9694:     return &start_data_table().
                   9695:            &start_data_table_header_row().
                   9696:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9697:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9698:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9699:            &end_data_table_header_row().
                   9700:            '<tr id="'.$id.'" style="display:none""><td>';
                   9701: }
                   9702: 
                   9703: sub end_togglebox {
                   9704:     return '</td></tr>'.&end_data_table();
                   9705: }
                   9706: 
1.1041    www      9707: sub LCprogressbar_script {
1.1302    raeburn  9708:    my ($id,$number_to_do)=@_;
                   9709:    if ($number_to_do) {
                   9710:        return(<<ENDPROGRESS);
1.1041    www      9711: <script type="text/javascript">
                   9712: // <![CDATA[
1.1045    www      9713: \$('#progressbar$id').progressbar({
1.1041    www      9714:   value: 0,
                   9715:   change: function(event, ui) {
                   9716:     var newVal = \$(this).progressbar('option', 'value');
                   9717:     \$('.pblabel', this).text(LCprogressTxt);
                   9718:   }
                   9719: });
                   9720: // ]]>
                   9721: </script>
                   9722: ENDPROGRESS
1.1302    raeburn  9723:    } else {
                   9724:        return(<<ENDPROGRESS);
                   9725: <script type="text/javascript">
                   9726: // <![CDATA[
                   9727: \$('#progressbar$id').progressbar({
                   9728:   value: false,
                   9729:   create: function(event, ui) {
                   9730:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9731:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9732:   }
                   9733: });
                   9734: // ]]>
                   9735: </script>
                   9736: ENDPROGRESS
                   9737:    }
1.1041    www      9738: }
                   9739: 
                   9740: sub LCprogressbarUpdate_script {
                   9741:    return(<<ENDPROGRESSUPDATE);
                   9742: <style type="text/css">
                   9743: .ui-progressbar { position:relative; }
1.1302    raeburn  9744: .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      9745: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9746: </style>
                   9747: <script type="text/javascript">
                   9748: // <![CDATA[
1.1045    www      9749: var LCprogressTxt='---';
                   9750: 
1.1302    raeburn  9751: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9752:    LCprogressTxt=progresstext;
1.1302    raeburn  9753:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9754:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9755:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9756:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9757:    } else {
                   9758:        \$('#progressbar'+id).progressbar('value',percent);
                   9759:    }
1.1041    www      9760: }
                   9761: // ]]>
                   9762: </script>
                   9763: ENDPROGRESSUPDATE
                   9764: }
                   9765: 
1.1042    www      9766: my $LClastpercent;
1.1045    www      9767: my $LCidcnt;
                   9768: my $LCcurrentid;
1.1042    www      9769: 
1.1041    www      9770: sub LCprogressbar {
1.1302    raeburn  9771:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9772:     $LClastpercent=0;
1.1045    www      9773:     $LCidcnt++;
                   9774:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9775:     my ($starting,$content);
                   9776:     if ($number_to_do) {
                   9777:         $starting=&mt('Starting');
                   9778:         $content=(<<ENDPROGBAR);
                   9779: $preamble
1.1045    www      9780:   <div id="progressbar$LCcurrentid">
1.1041    www      9781:     <span class="pblabel">$starting</span>
                   9782:   </div>
                   9783: ENDPROGBAR
1.1302    raeburn  9784:     } else {
                   9785:         $starting=&mt('Loading...');
                   9786:         $LClastpercent='false';
                   9787:         $content=(<<ENDPROGBAR);
                   9788: $preamble
                   9789:   <div id="progressbar$LCcurrentid">
                   9790:       <div class="progress-label">$starting</div>
                   9791:   </div>
                   9792: ENDPROGBAR
                   9793:     }
                   9794:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9795: }
                   9796: 
                   9797: sub LCprogressbarUpdate {
1.1302    raeburn  9798:     my ($r,$val,$text,$number_to_do)=@_;
                   9799:     if ($number_to_do) {
                   9800:         unless ($val) { 
                   9801:             if ($LClastpercent) {
                   9802:                 $val=$LClastpercent;
                   9803:             } else {
                   9804:                 $val=0;
                   9805:             }
                   9806:         }
                   9807:         if ($val<0) { $val=0; }
                   9808:         if ($val>100) { $val=0; }
                   9809:         $LClastpercent=$val;
                   9810:         unless ($text) { $text=$val.'%'; }
                   9811:     } else {
                   9812:         $val = 'false';
1.1042    www      9813:     }
1.1041    www      9814:     $text=&js_ready($text);
1.1044    www      9815:     &r_print($r,<<ENDUPDATE);
1.1041    www      9816: <script type="text/javascript">
                   9817: // <![CDATA[
1.1302    raeburn  9818: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9819: // ]]>
                   9820: </script>
                   9821: ENDUPDATE
1.1035    www      9822: }
                   9823: 
1.1042    www      9824: sub LCprogressbarClose {
                   9825:     my ($r)=@_;
                   9826:     $LClastpercent=0;
1.1044    www      9827:     &r_print($r,<<ENDCLOSE);
1.1042    www      9828: <script type="text/javascript">
                   9829: // <![CDATA[
1.1045    www      9830: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9831: // ]]>
                   9832: </script>
                   9833: ENDCLOSE
1.1044    www      9834: }
                   9835: 
                   9836: sub r_print {
                   9837:     my ($r,$to_print)=@_;
                   9838:     if ($r) {
                   9839:       $r->print($to_print);
                   9840:       $r->rflush();
                   9841:     } else {
                   9842:       print($to_print);
                   9843:     }
1.1042    www      9844: }
                   9845: 
1.320     albertel 9846: sub html_encode {
                   9847:     my ($result) = @_;
                   9848: 
1.322     albertel 9849:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9850:     
                   9851:     return $result;
                   9852: }
1.1044    www      9853: 
1.317     albertel 9854: sub js_ready {
                   9855:     my ($result) = @_;
                   9856: 
1.323     albertel 9857:     $result =~ s/[\n\r]/ /xmsg;
                   9858:     $result =~ s/\\/\\\\/xmsg;
                   9859:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9860:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9861:     
                   9862:     return $result;
                   9863: }
                   9864: 
1.315     albertel 9865: sub validate_page {
                   9866:     if (  exists($env{'internal.start_page'})
1.316     albertel 9867: 	  &&     $env{'internal.start_page'} > 1) {
                   9868: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9869: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9870: 				 $ENV{'request.filename'});
1.315     albertel 9871:     }
                   9872:     if (  exists($env{'internal.end_page'})
1.316     albertel 9873: 	  &&     $env{'internal.end_page'} > 1) {
                   9874: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9875: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9876: 				 $env{'request.filename'});
1.315     albertel 9877:     }
                   9878:     if (     exists($env{'internal.start_page'})
                   9879: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9880: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9881: 				 $env{'request.filename'});
1.315     albertel 9882:     }
                   9883:     if (   ! exists($env{'internal.start_page'})
                   9884: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9885: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9886: 				 $env{'request.filename'});
1.315     albertel 9887:     }
1.306     albertel 9888: }
1.315     albertel 9889: 
1.996     www      9890: 
                   9891: sub start_scrollbox {
1.1140    raeburn  9892:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9893:     unless ($outerwidth) { $outerwidth='520px'; }
                   9894:     unless ($width) { $width='500px'; }
                   9895:     unless ($height) { $height='200px'; }
1.1075    raeburn  9896:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9897:     if ($id ne '') {
1.1140    raeburn  9898:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9899:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9900:     }
1.1075    raeburn  9901:     if ($bgcolor ne '') {
                   9902:         $tdcol = "background-color: $bgcolor;";
                   9903:     }
1.1137    raeburn  9904:     my $nicescroll_js;
                   9905:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9906:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9907:     }
                   9908:     return <<"END";
                   9909: $nicescroll_js
                   9910: 
                   9911: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9912: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9913: END
                   9914: }
                   9915: 
                   9916: sub end_scrollbox {
                   9917:     return '</div></td></tr></table>';
                   9918: }
                   9919: 
                   9920: sub nicescroll_javascript {
                   9921:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9922:     my %options;
                   9923:     if (ref($cursor) eq 'HASH') {
                   9924:         %options = %{$cursor};
                   9925:     }
                   9926:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9927:         $options{'railalign'} = 'left';
                   9928:     }
                   9929:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9930:         my $function  = &get_users_function();
                   9931:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9932:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9933:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9934:         }
1.1140    raeburn  9935:     }
                   9936:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9937:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9938:             $options{'cursoropacity'}='1.0';
                   9939:         }
1.1140    raeburn  9940:     } else {
                   9941:         $options{'cursoropacity'}='1.0';
                   9942:     }
                   9943:     if ($options{'cursorfixedheight'} eq 'none') {
                   9944:         delete($options{'cursorfixedheight'});
                   9945:     } else {
                   9946:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9947:     }
                   9948:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9949:         delete($options{'railoffset'});
                   9950:     }
                   9951:     my @niceoptions;
                   9952:     while (my($key,$value) = each(%options)) {
                   9953:         if ($value =~ /^\{.+\}$/) {
                   9954:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9955:         } else {
1.1140    raeburn  9956:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9957:         }
1.1140    raeburn  9958:     }
                   9959:     my $nicescroll_js = '
1.1137    raeburn  9960: $(document).ready(
1.1140    raeburn  9961:       function() {
                   9962:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9963:       }
1.1137    raeburn  9964: );
                   9965: ';
1.1140    raeburn  9966:     if ($framecheck) {
                   9967:         $nicescroll_js .= '
                   9968: function expand_div(caller) {
                   9969:     if (top === self) {
                   9970:         document.getElementById("'.$id.'").style.width = "auto";
                   9971:         document.getElementById("'.$id.'").style.height = "auto";
                   9972:     } else {
                   9973:         try {
                   9974:             if (parent.frames) {
                   9975:                 if (parent.frames.length > 1) {
                   9976:                     var framesrc = parent.frames[1].location.href;
                   9977:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9978:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9979:                         document.getElementById("'.$id.'").style.width = "auto";
                   9980:                         document.getElementById("'.$id.'").style.height = "auto";
                   9981:                     }
                   9982:                 }
                   9983:             }
                   9984:         } catch (e) {
                   9985:             return;
                   9986:         }
1.1137    raeburn  9987:     }
1.1140    raeburn  9988:     return;
1.996     www      9989: }
1.1140    raeburn  9990: ';
                   9991:     }
                   9992:     if ($needjsready) {
                   9993:         $nicescroll_js = '
                   9994: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9995:     } else {
                   9996:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9997:     }
                   9998:     return $nicescroll_js;
1.996     www      9999: }
                   10000: 
1.318     albertel 10001: sub simple_error_page {
1.1150    bisitz   10002:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10003:     my %displayargs;
1.1151    raeburn  10004:     if (ref($args) eq 'HASH') {
                   10005:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10006:         if ($args->{'only_body'}) {
                   10007:             $displayargs{'only_body'} = 1;
                   10008:         }
                   10009:         if ($args->{'no_nav_bar'}) {
                   10010:             $displayargs{'no_nav_bar'} = 1;
                   10011:         }
1.1151    raeburn  10012:     } else {
                   10013:         $msg = &mt($msg);
                   10014:     }
1.1150    bisitz   10015: 
1.318     albertel 10016:     my $page =
1.1304    raeburn  10017: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10018: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10019: 	&Apache::loncommon::end_page();
                   10020:     if (ref($r)) {
                   10021: 	$r->print($page);
1.327     albertel 10022: 	return;
1.318     albertel 10023:     }
                   10024:     return $page;
                   10025: }
1.347     albertel 10026: 
                   10027: {
1.610     albertel 10028:     my @row_count;
1.961     onken    10029: 
                   10030:     sub start_data_table_count {
                   10031:         unshift(@row_count, 0);
                   10032:         return;
                   10033:     }
                   10034: 
                   10035:     sub end_data_table_count {
                   10036:         shift(@row_count);
                   10037:         return;
                   10038:     }
                   10039: 
1.347     albertel 10040:     sub start_data_table {
1.1018    raeburn  10041: 	my ($add_class,$id) = @_;
1.422     albertel 10042: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10043:         my $table_id;
                   10044:         if (defined($id)) {
                   10045:             $table_id = ' id="'.$id.'"';
                   10046:         }
1.961     onken    10047: 	&start_data_table_count();
1.1018    raeburn  10048: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10049:     }
                   10050: 
                   10051:     sub end_data_table {
1.961     onken    10052: 	&end_data_table_count();
1.389     albertel 10053: 	return '</table>'."\n";;
1.347     albertel 10054:     }
                   10055: 
                   10056:     sub start_data_table_row {
1.974     wenzelju 10057: 	my ($add_class, $id) = @_;
1.610     albertel 10058: 	$row_count[0]++;
                   10059: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10060: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10061:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10062:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10063:     }
1.471     banghart 10064:     
                   10065:     sub continue_data_table_row {
1.974     wenzelju 10066: 	my ($add_class, $id) = @_;
1.610     albertel 10067: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10068: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10069:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10070:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10071:     }
1.347     albertel 10072: 
                   10073:     sub end_data_table_row {
1.389     albertel 10074: 	return '</tr>'."\n";;
1.347     albertel 10075:     }
1.367     www      10076: 
1.421     albertel 10077:     sub start_data_table_empty_row {
1.707     bisitz   10078: #	$row_count[0]++;
1.421     albertel 10079: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10080:     }
                   10081: 
                   10082:     sub end_data_table_empty_row {
                   10083: 	return '</tr>'."\n";;
                   10084:     }
                   10085: 
1.367     www      10086:     sub start_data_table_header_row {
1.389     albertel 10087: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10088:     }
                   10089: 
                   10090:     sub end_data_table_header_row {
1.389     albertel 10091: 	return '</tr>'."\n";;
1.367     www      10092:     }
1.890     droeschl 10093: 
                   10094:     sub data_table_caption {
                   10095:         my $caption = shift;
                   10096:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10097:     }
1.347     albertel 10098: }
                   10099: 
1.548     albertel 10100: =pod
                   10101: 
                   10102: =item * &inhibit_menu_check($arg)
                   10103: 
                   10104: Checks for a inhibitmenu state and generates output to preserve it
                   10105: 
                   10106: Inputs:         $arg - can be any of
                   10107:                      - undef - in which case the return value is a string 
                   10108:                                to add  into arguments list of a uri
                   10109:                      - 'input' - in which case the return value is a HTML
                   10110:                                  <form> <input> field of type hidden to
                   10111:                                  preserve the value
                   10112:                      - a url - in which case the return value is the url with
                   10113:                                the neccesary cgi args added to preserve the
                   10114:                                inhibitmenu state
                   10115:                      - a ref to a url - no return value, but the string is
                   10116:                                         updated to include the neccessary cgi
                   10117:                                         args to preserve the inhibitmenu state
                   10118: 
                   10119: =cut
                   10120: 
                   10121: sub inhibit_menu_check {
                   10122:     my ($arg) = @_;
                   10123:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10124:     if ($arg eq 'input') {
                   10125: 	if ($env{'form.inhibitmenu'}) {
                   10126: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10127: 	} else {
                   10128: 	    return
                   10129: 	}
                   10130:     }
                   10131:     if ($env{'form.inhibitmenu'}) {
                   10132: 	if (ref($arg)) {
                   10133: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10134: 	} elsif ($arg eq '') {
                   10135: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10136: 	} else {
                   10137: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10138: 	}
                   10139:     }
                   10140:     if (!ref($arg)) {
                   10141: 	return $arg;
                   10142:     }
                   10143: }
                   10144: 
1.251     albertel 10145: ###############################################
1.182     matthew  10146: 
                   10147: =pod
                   10148: 
1.549     albertel 10149: =back
                   10150: 
                   10151: =head1 User Information Routines
                   10152: 
                   10153: =over 4
                   10154: 
1.405     albertel 10155: =item * &get_users_function()
1.182     matthew  10156: 
                   10157: Used by &bodytag to determine the current users primary role.
                   10158: Returns either 'student','coordinator','admin', or 'author'.
                   10159: 
                   10160: =cut
                   10161: 
                   10162: ###############################################
                   10163: sub get_users_function {
1.815     tempelho 10164:     my $function = 'norole';
1.818     tempelho 10165:     if ($env{'request.role'}=~/^(st)/) {
                   10166:         $function='student';
                   10167:     }
1.907     raeburn  10168:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10169:         $function='coordinator';
                   10170:     }
1.258     albertel 10171:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10172:         $function='admin';
                   10173:     }
1.826     bisitz   10174:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10175:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10176:         $function='author';
                   10177:     }
                   10178:     return $function;
1.54      www      10179: }
1.99      www      10180: 
                   10181: ###############################################
                   10182: 
1.233     raeburn  10183: =pod
                   10184: 
1.821     raeburn  10185: =item * &show_course()
                   10186: 
                   10187: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10188: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10189: 
                   10190: Inputs:
                   10191: None
                   10192: 
                   10193: Outputs:
                   10194: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10195: 
                   10196: =cut
                   10197: 
                   10198: ###############################################
                   10199: sub show_course {
                   10200:     my $course = !$env{'user.adv'};
                   10201:     if (!$env{'user.adv'}) {
                   10202:         foreach my $env (keys(%env)) {
                   10203:             next if ($env !~ m/^user\.priv\./);
                   10204:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10205:                 $course = 0;
                   10206:                 last;
                   10207:             }
                   10208:         }
                   10209:     }
                   10210:     return $course;
                   10211: }
                   10212: 
                   10213: ###############################################
                   10214: 
                   10215: =pod
                   10216: 
1.542     raeburn  10217: =item * &check_user_status()
1.274     raeburn  10218: 
                   10219: Determines current status of supplied role for a
                   10220: specific user. Roles can be active, previous or future.
                   10221: 
                   10222: Inputs: 
                   10223: user's domain, user's username, course's domain,
1.375     raeburn  10224: course's number, optional section ID.
1.274     raeburn  10225: 
                   10226: Outputs:
                   10227: role status: active, previous or future. 
                   10228: 
                   10229: =cut
                   10230: 
                   10231: sub check_user_status {
1.412     raeburn  10232:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10233:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10234:     my @uroles = keys(%userinfo);
1.274     raeburn  10235:     my $srchstr;
                   10236:     my $active_chk = 'none';
1.412     raeburn  10237:     my $now = time;
1.274     raeburn  10238:     if (@uroles > 0) {
1.908     raeburn  10239:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10240:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10241:         } else {
1.412     raeburn  10242:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10243:         }
                   10244:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10245:             my $role_end = 0;
                   10246:             my $role_start = 0;
                   10247:             $active_chk = 'active';
1.412     raeburn  10248:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10249:                 $role_end = $1;
                   10250:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10251:                     $role_start = $1;
1.274     raeburn  10252:                 }
                   10253:             }
                   10254:             if ($role_start > 0) {
1.412     raeburn  10255:                 if ($now < $role_start) {
1.274     raeburn  10256:                     $active_chk = 'future';
                   10257:                 }
                   10258:             }
                   10259:             if ($role_end > 0) {
1.412     raeburn  10260:                 if ($now > $role_end) {
1.274     raeburn  10261:                     $active_chk = 'previous';
                   10262:                 }
                   10263:             }
                   10264:         }
                   10265:     }
                   10266:     return $active_chk;
                   10267: }
                   10268: 
                   10269: ###############################################
                   10270: 
                   10271: =pod
                   10272: 
1.405     albertel 10273: =item * &get_sections()
1.233     raeburn  10274: 
                   10275: Determines all the sections for a course including
                   10276: sections with students and sections containing other roles.
1.419     raeburn  10277: Incoming parameters: 
                   10278: 
                   10279: 1. domain
                   10280: 2. course number 
                   10281: 3. reference to array containing roles for which sections should 
                   10282: be gathered (optional).
                   10283: 4. reference to array containing status types for which sections 
                   10284: should be gathered (optional).
                   10285: 
                   10286: If the third argument is undefined, sections are gathered for any role. 
                   10287: If the fourth argument is undefined, sections are gathered for any status.
                   10288: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10289:  
1.374     raeburn  10290: Returns section hash (keys are section IDs, values are
                   10291: number of users in each section), subject to the
1.419     raeburn  10292: optional roles filter, optional status filter 
1.233     raeburn  10293: 
                   10294: =cut
                   10295: 
                   10296: ###############################################
                   10297: sub get_sections {
1.419     raeburn  10298:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10299:     if (!defined($cdom) || !defined($cnum)) {
                   10300:         my $cid =  $env{'request.course.id'};
                   10301: 
                   10302: 	return if (!defined($cid));
                   10303: 
                   10304:         $cdom = $env{'course.'.$cid.'.domain'};
                   10305:         $cnum = $env{'course.'.$cid.'.num'};
                   10306:     }
                   10307: 
                   10308:     my %sectioncount;
1.419     raeburn  10309:     my $now = time;
1.240     albertel 10310: 
1.1118    raeburn  10311:     my $check_students = 1;
                   10312:     my $only_students = 0;
                   10313:     if (ref($possible_roles) eq 'ARRAY') {
                   10314:         if (grep(/^st$/,@{$possible_roles})) {
                   10315:             if (@{$possible_roles} == 1) {
                   10316:                 $only_students = 1;
                   10317:             }
                   10318:         } else {
                   10319:             $check_students = 0;
                   10320:         }
                   10321:     }
                   10322: 
                   10323:     if ($check_students) { 
1.276     albertel 10324: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10325: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10326: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10327:         my $start_index = &Apache::loncoursedata::CL_START();
                   10328:         my $end_index = &Apache::loncoursedata::CL_END();
                   10329:         my $status;
1.366     albertel 10330: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10331: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10332: 				                     $data->[$status_index],
                   10333:                                                      $data->[$start_index],
                   10334:                                                      $data->[$end_index]);
                   10335:             if ($stu_status eq 'Active') {
                   10336:                 $status = 'active';
                   10337:             } elsif ($end < $now) {
                   10338:                 $status = 'previous';
                   10339:             } elsif ($start > $now) {
                   10340:                 $status = 'future';
                   10341:             } 
                   10342: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10343:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10344:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10345: 		    $sectioncount{$section}++;
                   10346:                 }
1.240     albertel 10347: 	    }
                   10348: 	}
                   10349:     }
1.1118    raeburn  10350:     if ($only_students) {
                   10351:         return %sectioncount;
                   10352:     }
1.240     albertel 10353:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10354:     foreach my $user (sort(keys(%courseroles))) {
                   10355: 	if ($user !~ /^(\w{2})/) { next; }
                   10356: 	my ($role) = ($user =~ /^(\w{2})/);
                   10357: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10358: 	my ($section,$status);
1.240     albertel 10359: 	if ($role eq 'cr' &&
                   10360: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10361: 	    $section=$1;
                   10362: 	}
                   10363: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10364: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10365:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10366:         if ($end == -1 && $start == -1) {
                   10367:             next; #deleted role
                   10368:         }
                   10369:         if (!defined($possible_status)) { 
                   10370:             $sectioncount{$section}++;
                   10371:         } else {
                   10372:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10373:                 $status = 'active';
                   10374:             } elsif ($end < $now) {
                   10375:                 $status = 'future';
                   10376:             } elsif ($start > $now) {
                   10377:                 $status = 'previous';
                   10378:             }
                   10379:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10380:                 $sectioncount{$section}++;
                   10381:             }
                   10382:         }
1.233     raeburn  10383:     }
1.366     albertel 10384:     return %sectioncount;
1.233     raeburn  10385: }
                   10386: 
1.274     raeburn  10387: ###############################################
1.294     raeburn  10388: 
                   10389: =pod
1.405     albertel 10390: 
                   10391: =item * &get_course_users()
                   10392: 
1.275     raeburn  10393: Retrieves usernames:domains for users in the specified course
                   10394: with specific role(s), and access status. 
                   10395: 
                   10396: Incoming parameters:
1.277     albertel 10397: 1. course domain
                   10398: 2. course number
                   10399: 3. access status: users must have - either active, 
1.275     raeburn  10400: previous, future, or all.
1.277     albertel 10401: 4. reference to array of permissible roles
1.288     raeburn  10402: 5. reference to array of section restrictions (optional)
                   10403: 6. reference to results object (hash of hashes).
                   10404: 7. reference to optional userdata hash
1.609     raeburn  10405: 8. reference to optional statushash
1.630     raeburn  10406: 9. flag if privileged users (except those set to unhide in
                   10407:    course settings) should be excluded    
1.609     raeburn  10408: Keys of top level results hash are roles.
1.275     raeburn  10409: Keys of inner hashes are username:domain, with 
                   10410: values set to access type.
1.288     raeburn  10411: Optional userdata hash returns an array with arguments in the 
                   10412: same order as loncoursedata::get_classlist() for student data.
                   10413: 
1.609     raeburn  10414: Optional statushash returns
                   10415: 
1.288     raeburn  10416: Entries for end, start, section and status are blank because
                   10417: of the possibility of multiple values for non-student roles.
                   10418: 
1.275     raeburn  10419: =cut
1.405     albertel 10420: 
1.275     raeburn  10421: ###############################################
1.405     albertel 10422: 
1.275     raeburn  10423: sub get_course_users {
1.630     raeburn  10424:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10425:     my %idx = ();
1.419     raeburn  10426:     my %seclists;
1.288     raeburn  10427: 
                   10428:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10429:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10430:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10431:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10432:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10433:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10434:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10435:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10436: 
1.290     albertel 10437:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10438:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10439:         my $now = time;
1.277     albertel 10440:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10441:             my $match = 0;
1.412     raeburn  10442:             my $secmatch = 0;
1.419     raeburn  10443:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10444:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10445:             if ($section eq '') {
                   10446:                 $section = 'none';
                   10447:             }
1.291     albertel 10448:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10449:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10450:                     $secmatch = 1;
                   10451:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10452:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10453:                         $secmatch = 1;
                   10454:                     }
                   10455:                 } else {  
1.419     raeburn  10456: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10457: 		        $secmatch = 1;
                   10458:                     }
1.290     albertel 10459: 		}
1.412     raeburn  10460:                 if (!$secmatch) {
                   10461:                     next;
                   10462:                 }
1.419     raeburn  10463:             }
1.275     raeburn  10464:             if (defined($$types{'active'})) {
1.288     raeburn  10465:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10466:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10467:                     $match = 1;
1.275     raeburn  10468:                 }
                   10469:             }
                   10470:             if (defined($$types{'previous'})) {
1.609     raeburn  10471:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10472:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10473:                     $match = 1;
1.275     raeburn  10474:                 }
                   10475:             }
                   10476:             if (defined($$types{'future'})) {
1.609     raeburn  10477:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10478:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10479:                     $match = 1;
1.275     raeburn  10480:                 }
                   10481:             }
1.609     raeburn  10482:             if ($match) {
                   10483:                 push(@{$seclists{$student}},$section);
                   10484:                 if (ref($userdata) eq 'HASH') {
                   10485:                     $$userdata{$student} = $$classlist{$student};
                   10486:                 }
                   10487:                 if (ref($statushash) eq 'HASH') {
                   10488:                     $statushash->{$student}{'st'}{$section} = $status;
                   10489:                 }
1.288     raeburn  10490:             }
1.275     raeburn  10491:         }
                   10492:     }
1.412     raeburn  10493:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10494:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10495:         my $now = time;
1.609     raeburn  10496:         my %displaystatus = ( previous => 'Expired',
                   10497:                               active   => 'Active',
                   10498:                               future   => 'Future',
                   10499:                             );
1.1121    raeburn  10500:         my (%nothide,@possdoms);
1.630     raeburn  10501:         if ($hidepriv) {
                   10502:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10503:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10504:                 if ($user !~ /:/) {
                   10505:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10506:                 } else {
                   10507:                     $nothide{$user} = 1;
                   10508:                 }
                   10509:             }
1.1121    raeburn  10510:             my @possdoms = ($cdom);
                   10511:             if ($coursehash{'checkforpriv'}) {
                   10512:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10513:             }
1.630     raeburn  10514:         }
1.439     raeburn  10515:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10516:             my $match = 0;
1.412     raeburn  10517:             my $secmatch = 0;
1.439     raeburn  10518:             my $status;
1.412     raeburn  10519:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10520:             $user =~ s/:$//;
1.439     raeburn  10521:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10522:             if ($end == -1 || $start == -1) {
                   10523:                 next;
                   10524:             }
                   10525:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10526:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10527:                 my ($uname,$udom) = split(/:/,$user);
                   10528:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10529:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10530:                         $secmatch = 1;
                   10531:                     } elsif ($usec eq '') {
1.420     albertel 10532:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10533:                             $secmatch = 1;
                   10534:                         }
                   10535:                     } else {
                   10536:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10537:                             $secmatch = 1;
                   10538:                         }
                   10539:                     }
                   10540:                     if (!$secmatch) {
                   10541:                         next;
                   10542:                     }
1.288     raeburn  10543:                 }
1.419     raeburn  10544:                 if ($usec eq '') {
                   10545:                     $usec = 'none';
                   10546:                 }
1.275     raeburn  10547:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10548:                     if ($hidepriv) {
1.1121    raeburn  10549:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10550:                             (!$nothide{$uname.':'.$udom})) {
                   10551:                             next;
                   10552:                         }
                   10553:                     }
1.503     raeburn  10554:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10555:                         $status = 'previous';
                   10556:                     } elsif ($start > $now) {
                   10557:                         $status = 'future';
                   10558:                     } else {
                   10559:                         $status = 'active';
                   10560:                     }
1.277     albertel 10561:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10562:                         if ($status eq $type) {
1.420     albertel 10563:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10564:                                 push(@{$$users{$role}{$user}},$type);
                   10565:                             }
1.288     raeburn  10566:                             $match = 1;
                   10567:                         }
                   10568:                     }
1.419     raeburn  10569:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10570:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10571: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10572:                         }
1.420     albertel 10573:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10574:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10575:                         }
1.609     raeburn  10576:                         if (ref($statushash) eq 'HASH') {
                   10577:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10578:                         }
1.275     raeburn  10579:                     }
                   10580:                 }
                   10581:             }
                   10582:         }
1.290     albertel 10583:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10584:             if ((defined($cdom)) && (defined($cnum))) {
                   10585:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10586:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10587:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10588:                     next if ($owner eq '');
                   10589:                     my ($ownername,$ownerdom);
                   10590:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10591:                         $ownername = $1;
                   10592:                         $ownerdom = $2;
                   10593:                     } else {
                   10594:                         $ownername = $owner;
                   10595:                         $ownerdom = $cdom;
                   10596:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10597:                     }
                   10598:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10599:                     if (defined($userdata) && 
1.609     raeburn  10600: 			!exists($$userdata{$owner})) {
                   10601: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10602:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10603:                             push(@{$seclists{$owner}},'none');
                   10604:                         }
                   10605:                         if (ref($statushash) eq 'HASH') {
                   10606:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10607:                         }
1.290     albertel 10608: 		    }
1.279     raeburn  10609:                 }
                   10610:             }
                   10611:         }
1.419     raeburn  10612:         foreach my $user (keys(%seclists)) {
                   10613:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10614:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10615:         }
1.275     raeburn  10616:     }
                   10617:     return;
                   10618: }
                   10619: 
1.288     raeburn  10620: sub get_user_info {
                   10621:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10622:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10623: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10624:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10625:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10626:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10627:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10628:     return;
                   10629: }
1.275     raeburn  10630: 
1.472     raeburn  10631: ###############################################
                   10632: 
                   10633: =pod
                   10634: 
                   10635: =item * &get_user_quota()
                   10636: 
1.1134    raeburn  10637: Retrieves quota assigned for storage of user files.
                   10638: Default is to report quota for portfolio files.
1.472     raeburn  10639: 
                   10640: Incoming parameters:
                   10641: 1. user's username
                   10642: 2. user's domain
1.1134    raeburn  10643: 3. quota name - portfolio, author, or course
1.1136    raeburn  10644:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10645: 4. crstype - official, unofficial, textbook, placement or community, 
                   10646:    if quota name is course
1.472     raeburn  10647: 
                   10648: Returns:
1.1163    raeburn  10649: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10650: 2. (Optional) Type of setting: custom or default
                   10651:    (individually assigned or default for user's 
                   10652:    institutional status).
                   10653: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10654:    or student - types as defined in localenroll::inst_usertypes 
                   10655:    for user's domain, which determines default quota for user.
                   10656: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10657: 
                   10658: If a value has been stored in the user's environment, 
1.536     raeburn  10659: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10660: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10661: 
                   10662: =cut
                   10663: 
                   10664: ###############################################
                   10665: 
                   10666: 
                   10667: sub get_user_quota {
1.1136    raeburn  10668:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10669:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10670:     if (!defined($udom)) {
                   10671:         $udom = $env{'user.domain'};
                   10672:     }
                   10673:     if (!defined($uname)) {
                   10674:         $uname = $env{'user.name'};
                   10675:     }
                   10676:     if (($udom eq '' || $uname eq '') ||
                   10677:         ($udom eq 'public') && ($uname eq 'public')) {
                   10678:         $quota = 0;
1.536     raeburn  10679:         $quotatype = 'default';
                   10680:         $defquota = 0; 
1.472     raeburn  10681:     } else {
1.536     raeburn  10682:         my $inststatus;
1.1134    raeburn  10683:         if ($quotaname eq 'course') {
                   10684:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10685:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10686:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10687:             } else {
                   10688:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10689:                 $quota = $cenv{'internal.uploadquota'};
                   10690:             }
1.536     raeburn  10691:         } else {
1.1134    raeburn  10692:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10693:                 if ($quotaname eq 'author') {
                   10694:                     $quota = $env{'environment.authorquota'};
                   10695:                 } else {
                   10696:                     $quota = $env{'environment.portfolioquota'};
                   10697:                 }
                   10698:                 $inststatus = $env{'environment.inststatus'};
                   10699:             } else {
                   10700:                 my %userenv = 
                   10701:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10702:                                          'authorquota','inststatus'],$udom,$uname);
                   10703:                 my ($tmp) = keys(%userenv);
                   10704:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10705:                     if ($quotaname eq 'author') {
                   10706:                         $quota = $userenv{'authorquota'};
                   10707:                     } else {
                   10708:                         $quota = $userenv{'portfolioquota'};
                   10709:                     }
                   10710:                     $inststatus = $userenv{'inststatus'};
                   10711:                 } else {
                   10712:                     undef(%userenv);
                   10713:                 }
                   10714:             }
                   10715:         }
                   10716:         if ($quota eq '' || wantarray) {
                   10717:             if ($quotaname eq 'course') {
                   10718:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10719:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10720:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10721:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10722:                     $defquota = $domdefs{$crstype.'quota'};
                   10723:                 }
                   10724:                 if ($defquota eq '') {
                   10725:                     $defquota = 500;
                   10726:                 }
1.1134    raeburn  10727:             } else {
                   10728:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10729:             }
                   10730:             if ($quota eq '') {
                   10731:                 $quota = $defquota;
                   10732:                 $quotatype = 'default';
                   10733:             } else {
                   10734:                 $quotatype = 'custom';
                   10735:             }
1.472     raeburn  10736:         }
                   10737:     }
1.536     raeburn  10738:     if (wantarray) {
                   10739:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10740:     } else {
                   10741:         return $quota;
                   10742:     }
1.472     raeburn  10743: }
                   10744: 
                   10745: ###############################################
                   10746: 
                   10747: =pod
                   10748: 
                   10749: =item * &default_quota()
                   10750: 
1.536     raeburn  10751: Retrieves default quota assigned for storage of user portfolio files,
                   10752: given an (optional) user's institutional status.
1.472     raeburn  10753: 
                   10754: Incoming parameters:
1.1142    raeburn  10755: 
1.472     raeburn  10756: 1. domain
1.536     raeburn  10757: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10758:    status types (e.g., faculty, staff, student etc.)
                   10759:    which apply to the user for whom the default is being retrieved.
                   10760:    If the institutional status string in undefined, the domain
1.1134    raeburn  10761:    default quota will be returned.
                   10762: 3.  quota name - portfolio, author, or course
                   10763:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10764: 
                   10765: Returns:
1.1142    raeburn  10766: 
1.1163    raeburn  10767: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10768: 2. (Optional) institutional type which determined the value of the
                   10769:    default quota.
1.472     raeburn  10770: 
                   10771: If a value has been stored in the domain's configuration db,
                   10772: it will return that, otherwise it returns 20 (for backwards 
                   10773: compatibility with domains which have not set up a configuration
1.1163    raeburn  10774: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10775: 
1.536     raeburn  10776: If the user's status includes multiple types (e.g., staff and student),
                   10777: the largest default quota which applies to the user determines the
                   10778: default quota returned.
                   10779: 
1.472     raeburn  10780: =cut
                   10781: 
                   10782: ###############################################
                   10783: 
                   10784: 
                   10785: sub default_quota {
1.1134    raeburn  10786:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10787:     my ($defquota,$settingstatus);
                   10788:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10789:                                             ['quotas'],$udom);
1.1134    raeburn  10790:     my $key = 'defaultquota';
                   10791:     if ($quotaname eq 'author') {
                   10792:         $key = 'authorquota';
                   10793:     }
1.622     raeburn  10794:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10795:         if ($inststatus ne '') {
1.765     raeburn  10796:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10797:             foreach my $item (@statuses) {
1.1134    raeburn  10798:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10799:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10800:                         if ($defquota eq '') {
1.1134    raeburn  10801:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10802:                             $settingstatus = $item;
1.1134    raeburn  10803:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10804:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10805:                             $settingstatus = $item;
                   10806:                         }
                   10807:                     }
1.1134    raeburn  10808:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10809:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10810:                         if ($defquota eq '') {
                   10811:                             $defquota = $quotahash{'quotas'}{$item};
                   10812:                             $settingstatus = $item;
                   10813:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10814:                             $defquota = $quotahash{'quotas'}{$item};
                   10815:                             $settingstatus = $item;
                   10816:                         }
1.536     raeburn  10817:                     }
                   10818:                 }
                   10819:             }
                   10820:         }
                   10821:         if ($defquota eq '') {
1.1134    raeburn  10822:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10823:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10824:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10825:                 $defquota = $quotahash{'quotas'}{'default'};
                   10826:             }
1.536     raeburn  10827:             $settingstatus = 'default';
1.1139    raeburn  10828:             if ($defquota eq '') {
                   10829:                 if ($quotaname eq 'author') {
                   10830:                     $defquota = 500;
                   10831:                 }
                   10832:             }
1.536     raeburn  10833:         }
                   10834:     } else {
                   10835:         $settingstatus = 'default';
1.1134    raeburn  10836:         if ($quotaname eq 'author') {
                   10837:             $defquota = 500;
                   10838:         } else {
                   10839:             $defquota = 20;
                   10840:         }
1.536     raeburn  10841:     }
                   10842:     if (wantarray) {
                   10843:         return ($defquota,$settingstatus);
1.472     raeburn  10844:     } else {
1.536     raeburn  10845:         return $defquota;
1.472     raeburn  10846:     }
                   10847: }
                   10848: 
1.1135    raeburn  10849: ###############################################
                   10850: 
                   10851: =pod
                   10852: 
1.1136    raeburn  10853: =item * &excess_filesize_warning()
1.1135    raeburn  10854: 
                   10855: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10856: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10857: space to be exceeded.
1.1136    raeburn  10858: 
                   10859: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10860: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10861: 
1.1165    raeburn  10862: Inputs: 7 
1.1136    raeburn  10863: 1. username or coursenum
1.1135    raeburn  10864: 2. domain
1.1136    raeburn  10865: 3. context ('author' or 'course')
1.1135    raeburn  10866: 4. filename of file for which action is being requested
                   10867: 5. filesize (kB) of file
                   10868: 6. action being taken: copy or upload.
1.1237    raeburn  10869: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10870: 
                   10871: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10872:          otherwise return null.
                   10873: 
                   10874: =back
1.1135    raeburn  10875: 
                   10876: =cut
                   10877: 
1.1136    raeburn  10878: sub excess_filesize_warning {
1.1165    raeburn  10879:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10880:     my $current_disk_usage = 0;
1.1165    raeburn  10881:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10882:     if ($context eq 'author') {
                   10883:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10884:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10885:     } else {
                   10886:         foreach my $subdir ('docs','supplemental') {
                   10887:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10888:         }
                   10889:     }
1.1135    raeburn  10890:     $disk_quota = int($disk_quota * 1000);
                   10891:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10892:         return '<p class="LC_warning">'.
1.1135    raeburn  10893:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10894:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10895:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10896:                             $disk_quota,$current_disk_usage).
                   10897:                '</p>';
                   10898:     }
                   10899:     return;
                   10900: }
                   10901: 
                   10902: ###############################################
                   10903: 
                   10904: 
1.1136    raeburn  10905: 
                   10906: 
1.384     raeburn  10907: sub get_secgrprole_info {
                   10908:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10909:     my %sections_count = &get_sections($cdom,$cnum);
                   10910:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10911:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10912:     my @groups = sort(keys(%curr_groups));
                   10913:     my $allroles = [];
                   10914:     my $rolehash;
                   10915:     my $accesshash = {
                   10916:                      active => 'Currently has access',
                   10917:                      future => 'Will have future access',
                   10918:                      previous => 'Previously had access',
                   10919:                   };
                   10920:     if ($needroles) {
                   10921:         $rolehash = {'all' => 'all'};
1.385     albertel 10922:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10923: 	if (&Apache::lonnet::error(%user_roles)) {
                   10924: 	    undef(%user_roles);
                   10925: 	}
                   10926:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10927:             my ($role)=split(/\:/,$item,2);
                   10928:             if ($role eq 'cr') { next; }
                   10929:             if ($role =~ /^cr/) {
                   10930:                 $$rolehash{$role} = (split('/',$role))[3];
                   10931:             } else {
                   10932:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10933:             }
                   10934:         }
                   10935:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10936:             push(@{$allroles},$key);
                   10937:         }
                   10938:         push (@{$allroles},'st');
                   10939:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10940:     }
                   10941:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10942: }
                   10943: 
1.555     raeburn  10944: sub user_picker {
1.1279    raeburn  10945:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10946:     my $currdom = $dom;
1.1253    raeburn  10947:     my @alldoms = &Apache::lonnet::all_domains();
                   10948:     if (@alldoms == 1) {
                   10949:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10950:                                                ['directorysrch'],$alldoms[0]);
                   10951:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10952:         my $showdom = $domdesc;
                   10953:         if ($showdom eq '') {
                   10954:             $showdom = $dom;
                   10955:         }
                   10956:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10957:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10958:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10959:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10960:             }
                   10961:         }
                   10962:     }
1.555     raeburn  10963:     my %curr_selected = (
                   10964:                         srchin => 'dom',
1.580     raeburn  10965:                         srchby => 'lastname',
1.555     raeburn  10966:                       );
                   10967:     my $srchterm;
1.625     raeburn  10968:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10969:         if ($srch->{'srchby'} ne '') {
                   10970:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10971:         }
                   10972:         if ($srch->{'srchin'} ne '') {
                   10973:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10974:         }
                   10975:         if ($srch->{'srchtype'} ne '') {
                   10976:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10977:         }
                   10978:         if ($srch->{'srchdomain'} ne '') {
                   10979:             $currdom = $srch->{'srchdomain'};
                   10980:         }
                   10981:         $srchterm = $srch->{'srchterm'};
                   10982:     }
1.1222    damieng  10983:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10984:                     'usr'       => 'Search criteria',
1.563     raeburn  10985:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10986:                     'uname'     => 'username',
                   10987:                     'lastname'  => 'last name',
1.555     raeburn  10988:                     'lastfirst' => 'last name, first name',
1.558     albertel 10989:                     'crs'       => 'in this course',
1.576     raeburn  10990:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10991:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10992:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10993:                     'exact'     => 'is',
                   10994:                     'contains'  => 'contains',
1.569     raeburn  10995:                     'begins'    => 'begins with',
1.1222    damieng  10996:                                        );
                   10997:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10998:                     'youm'      => "You must include some text to search for.",
                   10999:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11000:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11001:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11002:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11003:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11004:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11005:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11006:                                        );
1.1222    damieng  11007:     &html_escape(\%html_lt);
                   11008:     &js_escape(\%js_lt);
1.1255    raeburn  11009:     my $domform;
1.1277    raeburn  11010:     my $allow_blank = 1;
1.1255    raeburn  11011:     if ($fixeddom) {
1.1277    raeburn  11012:         $allow_blank = 0;
                   11013:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11014:     } else {
1.1287    raeburn  11015:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11016:         my ($trusted,$untrusted);
1.1287    raeburn  11017:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11018:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11019:         } elsif ($context eq 'author') {
1.1288    raeburn  11020:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11021:         } elsif ($context eq 'domain') {
1.1288    raeburn  11022:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11023:         }
1.1288    raeburn  11024:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11025:     }
1.563     raeburn  11026:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11027: 
                   11028:     my @srchins = ('crs','dom','alc','instd');
                   11029: 
                   11030:     foreach my $option (@srchins) {
                   11031:         # FIXME 'alc' option unavailable until 
                   11032:         #       loncreateuser::print_user_query_page()
                   11033:         #       has been completed.
                   11034:         next if ($option eq 'alc');
1.880     raeburn  11035:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11036:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11037:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11038:         if ($curr_selected{'srchin'} eq $option) {
                   11039:             $srchinsel .= ' 
1.1222    damieng  11040:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11041:         } else {
                   11042:             $srchinsel .= '
1.1222    damieng  11043:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11044:         }
1.555     raeburn  11045:     }
1.563     raeburn  11046:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11047: 
                   11048:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11049:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11050:         if ($curr_selected{'srchby'} eq $option) {
                   11051:             $srchbysel .= '
1.1222    damieng  11052:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11053:         } else {
                   11054:             $srchbysel .= '
1.1222    damieng  11055:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11056:          }
                   11057:     }
                   11058:     $srchbysel .= "\n  </select>\n";
                   11059: 
                   11060:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11061:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11062:         if ($curr_selected{'srchtype'} eq $option) {
                   11063:             $srchtypesel .= '
1.1222    damieng  11064:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11065:         } else {
                   11066:             $srchtypesel .= '
1.1222    damieng  11067:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11068:         }
                   11069:     }
                   11070:     $srchtypesel .= "\n  </select>\n";
                   11071: 
1.558     albertel 11072:     my ($newuserscript,$new_user_create);
1.994     raeburn  11073:     my $context_dom = $env{'request.role.domain'};
                   11074:     if ($context eq 'requestcrs') {
                   11075:         if ($env{'form.coursedom'} ne '') { 
                   11076:             $context_dom = $env{'form.coursedom'};
                   11077:         }
                   11078:     }
1.556     raeburn  11079:     if ($forcenewuser) {
1.576     raeburn  11080:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11081:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11082:                 if ($cancreate) {
                   11083:                     $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>';
                   11084:                 } else {
1.799     bisitz   11085:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11086:                     my %usertypetext = (
                   11087:                         official   => 'institutional',
                   11088:                         unofficial => 'non-institutional',
                   11089:                     );
1.799     bisitz   11090:                     $new_user_create = '<p class="LC_warning">'
                   11091:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11092:                                       .' '
                   11093:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11094:                                           ,'<a href="'.$helplink.'">','</a>')
                   11095:                                       .'</p><br />';
1.627     raeburn  11096:                 }
1.576     raeburn  11097:             }
                   11098:         }
                   11099: 
1.556     raeburn  11100:         $newuserscript = <<"ENDSCRIPT";
                   11101: 
1.570     raeburn  11102: function setSearch(createnew,callingForm) {
1.556     raeburn  11103:     if (createnew == 1) {
1.570     raeburn  11104:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11105:             if (callingForm.srchby.options[i].value == 'uname') {
                   11106:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11107:             }
                   11108:         }
1.570     raeburn  11109:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11110:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11111: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11112:             }
                   11113:         }
1.570     raeburn  11114:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11115:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11116:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11117:             }
                   11118:         }
1.570     raeburn  11119:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11120:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11121:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11122:             }
                   11123:         }
                   11124:     }
                   11125: }
                   11126: ENDSCRIPT
1.558     albertel 11127: 
1.556     raeburn  11128:     }
                   11129: 
1.555     raeburn  11130:     my $output = <<"END_BLOCK";
1.556     raeburn  11131: <script type="text/javascript">
1.824     bisitz   11132: // <![CDATA[
1.570     raeburn  11133: function validateEntry(callingForm) {
1.558     albertel 11134: 
1.556     raeburn  11135:     var checkok = 1;
1.558     albertel 11136:     var srchin;
1.570     raeburn  11137:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11138: 	if ( callingForm.srchin[i].checked ) {
                   11139: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11140: 	}
                   11141:     }
                   11142: 
1.570     raeburn  11143:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11144:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11145:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11146:     var srchterm =  callingForm.srchterm.value;
                   11147:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11148:     var msg = "";
                   11149: 
                   11150:     if (srchterm == "") {
                   11151:         checkok = 0;
1.1222    damieng  11152:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11153:     }
                   11154: 
1.569     raeburn  11155:     if (srchtype== 'begins') {
                   11156:         if (srchterm.length < 2) {
                   11157:             checkok = 0;
1.1222    damieng  11158:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11159:         }
                   11160:     }
                   11161: 
1.556     raeburn  11162:     if (srchtype== 'contains') {
                   11163:         if (srchterm.length < 3) {
                   11164:             checkok = 0;
1.1222    damieng  11165:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11166:         }
                   11167:     }
                   11168:     if (srchin == 'instd') {
                   11169:         if (srchdomain == '') {
                   11170:             checkok = 0;
1.1222    damieng  11171:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11172:         }
                   11173:     }
                   11174:     if (srchin == 'dom') {
                   11175:         if (srchdomain == '') {
                   11176:             checkok = 0;
1.1222    damieng  11177:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11178:         }
                   11179:     }
                   11180:     if (srchby == 'lastfirst') {
                   11181:         if (srchterm.indexOf(",") == -1) {
                   11182:             checkok = 0;
1.1222    damieng  11183:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11184:         }
                   11185:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11186:             checkok = 0;
1.1222    damieng  11187:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11188:         }
                   11189:     }
                   11190:     if (checkok == 0) {
1.1222    damieng  11191:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11192:         return;
                   11193:     }
                   11194:     if (checkok == 1) {
1.570     raeburn  11195:         callingForm.submit();
1.556     raeburn  11196:     }
                   11197: }
                   11198: 
                   11199: $newuserscript
                   11200: 
1.824     bisitz   11201: // ]]>
1.556     raeburn  11202: </script>
1.558     albertel 11203: 
                   11204: $new_user_create
                   11205: 
1.555     raeburn  11206: END_BLOCK
1.558     albertel 11207: 
1.876     raeburn  11208:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11209:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11210:                $domform.
                   11211:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11212:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11213:                $srchbysel.
                   11214:                $srchtypesel. 
                   11215:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11216:                $srchinsel.
                   11217:                &Apache::lonhtmlcommon::row_closure(1). 
                   11218:                &Apache::lonhtmlcommon::end_pick_box().
                   11219:                '<br />';
1.1253    raeburn  11220:     return ($output,1);
1.555     raeburn  11221: }
                   11222: 
1.612     raeburn  11223: sub user_rule_check {
1.615     raeburn  11224:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11225:     my ($response,%inst_response);
1.612     raeburn  11226:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11227:         if (keys(%{$usershash}) > 1) {
                   11228:             my (%by_username,%by_id,%userdoms);
                   11229:             my $checkid; 
                   11230:             if (ref($checks) eq 'HASH') {
                   11231:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11232:                     $checkid = 1;
                   11233:                 }
                   11234:             }
                   11235:             foreach my $user (keys(%{$usershash})) {
                   11236:                 my ($uname,$udom) = split(/:/,$user);
                   11237:                 if ($checkid) {
                   11238:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11239:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11240:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11241:                             $userdoms{$udom} = 1;
1.1227    raeburn  11242:                             if (ref($inst_results) eq 'HASH') {
                   11243:                                 $inst_results->{$uname.':'.$udom} = {};
                   11244:                             }
1.1226    raeburn  11245:                         }
                   11246:                     }
                   11247:                 } else {
                   11248:                     $by_username{$udom}{$uname} = 1;
                   11249:                     $userdoms{$udom} = 1;
1.1227    raeburn  11250:                     if (ref($inst_results) eq 'HASH') {
                   11251:                         $inst_results->{$uname.':'.$udom} = {};
                   11252:                     }
1.1226    raeburn  11253:                 }
                   11254:             }
                   11255:             foreach my $udom (keys(%userdoms)) {
                   11256:                 if (!$got_rules->{$udom}) {
                   11257:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11258:                                                              ['usercreation'],$udom);
                   11259:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11260:                         foreach my $item ('username','id') {
                   11261:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11262:                                 $$curr_rules{$udom}{$item} =
                   11263:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11264:                             }
                   11265:                         }
                   11266:                     }
                   11267:                     $got_rules->{$udom} = 1;
                   11268:                 }
1.612     raeburn  11269:             }
1.1226    raeburn  11270:             if ($checkid) {
                   11271:                 foreach my $udom (keys(%by_id)) {
                   11272:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11273:                     if ($outcome eq 'ok') {
1.1227    raeburn  11274:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11275:                             my $uname = $by_id{$udom}{$id};
                   11276:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11277:                         }
1.1226    raeburn  11278:                         if (ref($results) eq 'HASH') {
                   11279:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11280:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11281:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11282:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11283:                                 }
1.1226    raeburn  11284:                             }
                   11285:                         }
                   11286:                     }
1.612     raeburn  11287:                 }
1.615     raeburn  11288:             } else {
1.1226    raeburn  11289:                 foreach my $udom (keys(%by_username)) {
                   11290:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11291:                     if ($outcome eq 'ok') {
1.1227    raeburn  11292:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11293:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11294:                         }
1.1226    raeburn  11295:                         if (ref($results) eq 'HASH') {
                   11296:                             foreach my $uname (keys(%{$results})) {
                   11297:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11298:                             }
                   11299:                         }
                   11300:                     }
                   11301:                 }
1.612     raeburn  11302:             }
1.1226    raeburn  11303:         } elsif (keys(%{$usershash}) == 1) {
                   11304:             my $user = (keys(%{$usershash}))[0];
                   11305:             my ($uname,$udom) = split(/:/,$user);
                   11306:             if (($udom ne '') && ($uname ne '')) {
                   11307:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11308:                     if (ref($checks) eq 'HASH') {
                   11309:                         if (defined($checks->{'username'})) {
                   11310:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11311:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11312:                         } elsif (defined($checks->{'id'})) {
                   11313:                             if ($usershash->{$user}->{'id'} ne '') {
                   11314:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11315:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11316:                                                                   $usershash->{$user}->{'id'});
                   11317:                             } else {
                   11318:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11319:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11320:                             }
1.585     raeburn  11321:                         }
1.1226    raeburn  11322:                     } else {
                   11323:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11324:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11325:                        return;
                   11326:                     }
                   11327:                     if (!$got_rules->{$udom}) {
                   11328:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11329:                                                                  ['usercreation'],$udom);
                   11330:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11331:                             foreach my $item ('username','id') {
                   11332:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11333:                                    $$curr_rules{$udom}{$item} = 
                   11334:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11335:                                 }
                   11336:                             }
                   11337:                         }
                   11338:                         $got_rules->{$udom} = 1;
1.585     raeburn  11339:                     }
                   11340:                 }
1.1226    raeburn  11341:             } else {
                   11342:                 return;
                   11343:             }
                   11344:         } else {
                   11345:             return;
                   11346:         }
                   11347:         foreach my $user (keys(%{$usershash})) {
                   11348:             my ($uname,$udom) = split(/:/,$user);
                   11349:             next if (($udom eq '') || ($uname eq ''));
                   11350:             my $id;
1.1227    raeburn  11351:             if (ref($inst_results) eq 'HASH') {
                   11352:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11353:                     $id = $inst_results->{$user}->{'id'};
                   11354:                 }
                   11355:             }
                   11356:             if ($id eq '') { 
                   11357:                 if (ref($usershash->{$user})) {
                   11358:                     $id = $usershash->{$user}->{'id'};
                   11359:                 }
1.585     raeburn  11360:             }
1.612     raeburn  11361:             foreach my $item (keys(%{$checks})) {
                   11362:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11363:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11364:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11365:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11366:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11367:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11368:                                 if ($rule_check{$rule}) {
                   11369:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11370:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11371:                                         if (ref($inst_results) eq 'HASH') {
                   11372:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11373:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11374:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11375:                                                 } elsif ($item eq 'id') {
                   11376:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11377:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11378:                                                     }
1.615     raeburn  11379:                                                 }
1.612     raeburn  11380:                                             }
                   11381:                                         }
1.615     raeburn  11382:                                     }
                   11383:                                     last;
1.585     raeburn  11384:                                 }
                   11385:                             }
                   11386:                         }
                   11387:                     }
                   11388:                 }
                   11389:             }
                   11390:         }
                   11391:     }
1.612     raeburn  11392:     return;
                   11393: }
                   11394: 
                   11395: sub user_rule_formats {
                   11396:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11397:     my %text = ( 
                   11398:                  'username' => 'Usernames',
                   11399:                  'id'       => 'IDs',
                   11400:                );
                   11401:     my $output;
                   11402:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11403:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11404:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11405:             $output = '<br />'.
                   11406:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11407:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11408:                       ' <ul>';
1.612     raeburn  11409:             foreach my $rule (@{$ruleorder}) {
                   11410:                 if (ref($curr_rules) eq 'ARRAY') {
                   11411:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11412:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11413:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11414:                                         $rules->{$rule}{'desc'}.'</li>';
                   11415:                         }
                   11416:                     }
                   11417:                 }
                   11418:             }
                   11419:             $output .= '</ul>';
                   11420:         }
                   11421:     }
                   11422:     return $output;
                   11423: }
                   11424: 
                   11425: sub instrule_disallow_msg {
1.615     raeburn  11426:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11427:     my $response;
                   11428:     my %text = (
                   11429:                   item   => 'username',
                   11430:                   items  => 'usernames',
                   11431:                   match  => 'matches',
                   11432:                   do     => 'does',
                   11433:                   action => 'a username',
                   11434:                   one    => 'one',
                   11435:                );
                   11436:     if ($count > 1) {
                   11437:         $text{'item'} = 'usernames';
                   11438:         $text{'match'} ='match';
                   11439:         $text{'do'} = 'do';
                   11440:         $text{'action'} = 'usernames',
                   11441:         $text{'one'} = 'ones';
                   11442:     }
                   11443:     if ($checkitem eq 'id') {
                   11444:         $text{'items'} = 'IDs';
                   11445:         $text{'item'} = 'ID';
                   11446:         $text{'action'} = 'an ID';
1.615     raeburn  11447:         if ($count > 1) {
                   11448:             $text{'item'} = 'IDs';
                   11449:             $text{'action'} = 'IDs';
                   11450:         }
1.612     raeburn  11451:     }
1.674     bisitz   11452:     $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  11453:     if ($mode eq 'upload') {
                   11454:         if ($checkitem eq 'username') {
                   11455:             $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'}.");
                   11456:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11457:             $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  11458:         }
1.669     raeburn  11459:     } elsif ($mode eq 'selfcreate') {
                   11460:         if ($checkitem eq 'id') {
                   11461:             $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.");
                   11462:         }
1.615     raeburn  11463:     } else {
                   11464:         if ($checkitem eq 'username') {
                   11465:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11466:         } elsif ($checkitem eq 'id') {
                   11467:             $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.");
                   11468:         }
1.612     raeburn  11469:     }
                   11470:     return $response;
1.585     raeburn  11471: }
                   11472: 
1.624     raeburn  11473: sub personal_data_fieldtitles {
                   11474:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11475:                         id => 'Student/Employee ID',
                   11476:                         permanentemail => 'E-mail address',
                   11477:                         lastname => 'Last Name',
                   11478:                         firstname => 'First Name',
                   11479:                         middlename => 'Middle Name',
                   11480:                         generation => 'Generation',
                   11481:                         gen => 'Generation',
1.765     raeburn  11482:                         inststatus => 'Affiliation',
1.624     raeburn  11483:                    );
                   11484:     return %fieldtitles;
                   11485: }
                   11486: 
1.642     raeburn  11487: sub sorted_inst_types {
                   11488:     my ($dom) = @_;
1.1185    raeburn  11489:     my ($usertypes,$order);
                   11490:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11491:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11492:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11493:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11494:     } else {
                   11495:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11496:     }
1.642     raeburn  11497:     my $othertitle = &mt('All users');
                   11498:     if ($env{'request.course.id'}) {
1.668     raeburn  11499:         $othertitle  = &mt('Any users');
1.642     raeburn  11500:     }
                   11501:     my @types;
                   11502:     if (ref($order) eq 'ARRAY') {
                   11503:         @types = @{$order};
                   11504:     }
                   11505:     if (@types == 0) {
                   11506:         if (ref($usertypes) eq 'HASH') {
                   11507:             @types = sort(keys(%{$usertypes}));
                   11508:         }
                   11509:     }
                   11510:     if (keys(%{$usertypes}) > 0) {
                   11511:         $othertitle = &mt('Other users');
                   11512:     }
                   11513:     return ($othertitle,$usertypes,\@types);
                   11514: }
                   11515: 
1.645     raeburn  11516: sub get_institutional_codes {
1.1361    raeburn  11517:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11518: # Get complete list of course sections to update
                   11519:     my @currsections = ();
                   11520:     my @currxlists = ();
1.1361    raeburn  11521:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11522:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11523:     my $crskey = $crs.':'.$coursecode;
                   11524:     @{$unclutteredsec{$crskey}} = ();
                   11525:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11526: 
                   11527:     if ($$settings{'internal.sectionnums'} ne '') {
                   11528:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11529:     }
                   11530: 
                   11531:     if ($$settings{'internal.crosslistings'} ne '') {
                   11532:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11533:     }
                   11534: 
                   11535:     if (@currxlists > 0) {
1.1361    raeburn  11536:         foreach my $xl (@currxlists) {
                   11537:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11538:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11539:                     push(@{$allcourses},$1);
1.645     raeburn  11540:                     $$LC_code{$1} = $2;
                   11541:                 }
                   11542:             }
                   11543:         }
                   11544:     }
1.1361    raeburn  11545: 
1.645     raeburn  11546:     if (@currsections > 0) {
1.1361    raeburn  11547:         foreach my $sec (@currsections) {
                   11548:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11549:                 my $instsec = $1;
1.645     raeburn  11550:                 my $lc_sec = $2;
1.1361    raeburn  11551:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11552:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11553:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11554:                 }
                   11555:             }
                   11556:         }
                   11557:     }
                   11558: 
                   11559:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11560:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11561:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11562:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11563:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11564:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11565:                     push(@{$allcourses},$sec);
1.1361    raeburn  11566:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11567:                 }
                   11568:             }
                   11569:         }
                   11570:     }
                   11571:     return;
                   11572: }
                   11573: 
1.971     raeburn  11574: sub get_standard_codeitems {
                   11575:     return ('Year','Semester','Department','Number','Section');
                   11576: }
                   11577: 
1.112     bowersj2 11578: =pod
                   11579: 
1.780     raeburn  11580: =head1 Slot Helpers
                   11581: 
                   11582: =over 4
                   11583: 
                   11584: =item * sorted_slots()
                   11585: 
1.1040    raeburn  11586: Sorts an array of slot names in order of an optional sort key,
                   11587: default sort is by slot start time (earliest first). 
1.780     raeburn  11588: 
                   11589: Inputs:
                   11590: 
                   11591: =over 4
                   11592: 
                   11593: slotsarr  - Reference to array of unsorted slot names.
                   11594: 
                   11595: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11596: 
1.1040    raeburn  11597: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11598: 
1.549     albertel 11599: =back
                   11600: 
1.780     raeburn  11601: Returns:
                   11602: 
                   11603: =over 4
                   11604: 
1.1040    raeburn  11605: sorted   - An array of slot names sorted by a specified sort key 
                   11606:            (default sort key is start time of the slot).
1.780     raeburn  11607: 
                   11608: =back
                   11609: 
                   11610: =cut
                   11611: 
                   11612: 
                   11613: sub sorted_slots {
1.1040    raeburn  11614:     my ($slotsarr,$slots,$sortkey) = @_;
                   11615:     if ($sortkey eq '') {
                   11616:         $sortkey = 'starttime';
                   11617:     }
1.780     raeburn  11618:     my @sorted;
                   11619:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11620:         @sorted =
                   11621:             sort {
                   11622:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11623:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11624:                      }
                   11625:                      if (ref($slots->{$a})) { return -1;}
                   11626:                      if (ref($slots->{$b})) { return 1;}
                   11627:                      return 0;
                   11628:                  } @{$slotsarr};
                   11629:     }
                   11630:     return @sorted;
                   11631: }
                   11632: 
1.1040    raeburn  11633: =pod
                   11634: 
                   11635: =item * get_future_slots()
                   11636: 
                   11637: Inputs:
                   11638: 
                   11639: =over 4
                   11640: 
                   11641: cnum - course number
                   11642: 
                   11643: cdom - course domain
                   11644: 
                   11645: now - current UNIX time
                   11646: 
                   11647: symb - optional symb
                   11648: 
                   11649: =back
                   11650: 
                   11651: Returns:
                   11652: 
                   11653: =over 4
                   11654: 
                   11655: sorted_reservable - ref to array of student_schedulable slots currently 
                   11656:                     reservable, ordered by end date of reservation period.
                   11657: 
                   11658: reservable_now - ref to hash of student_schedulable slots currently
                   11659:                  reservable.
                   11660: 
                   11661:     Keys in inner hash are:
                   11662:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11663:     (b) endreserve: end date of reservation period.
                   11664:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11665:         selected.
1.1040    raeburn  11666: 
                   11667: sorted_future - ref to array of student_schedulable slots reservable in
                   11668:                 the future, ordered by start date of reservation period.
                   11669: 
                   11670: future_reservable - ref to hash of student_schedulable slots reservable
                   11671:                     in the future.
                   11672: 
                   11673:     Keys in inner hash are:
                   11674:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11675:     (b) startreserve: start date of reservation period.
                   11676:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11677:         selected.
1.1040    raeburn  11678: 
                   11679: =back
                   11680: 
                   11681: =cut
                   11682: 
                   11683: sub get_future_slots {
                   11684:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11685:     my $map;
                   11686:     if ($symb) {
                   11687:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11688:     }
1.1040    raeburn  11689:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11690:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11691:     foreach my $slot (keys(%slots)) {
                   11692:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11693:         if ($symb) {
1.1229    raeburn  11694:             if ($slots{$slot}->{'symb'} ne '') {
                   11695:                 my $canuse;
                   11696:                 my %oksymbs;
                   11697:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11698:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11699:                 if ($oksymbs{$symb}) {
                   11700:                     $canuse = 1;
                   11701:                 } else {
                   11702:                     foreach my $item (@slotsymbs) {
                   11703:                         if ($item =~ /\.(page|sequence)$/) {
                   11704:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11705:                             if (($map ne '') && ($map eq $sloturl)) {
                   11706:                                 $canuse = 1;
                   11707:                                 last;
                   11708:                             }
                   11709:                         }
                   11710:                     }
                   11711:                 }
                   11712:                 next unless ($canuse);
                   11713:             }
1.1040    raeburn  11714:         }
                   11715:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11716:             ($slots{$slot}->{'endtime'} > $now)) {
                   11717:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11718:                 my $userallowed = 0;
                   11719:                 if ($slots{$slot}->{'allowedsections'}) {
                   11720:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11721:                     if (!defined($env{'request.role.sec'})
                   11722:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11723:                         $userallowed=1;
                   11724:                     } else {
                   11725:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11726:                             $userallowed=1;
                   11727:                         }
                   11728:                     }
                   11729:                     unless ($userallowed) {
                   11730:                         if (defined($env{'request.course.groups'})) {
                   11731:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11732:                             foreach my $group (@groups) {
                   11733:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11734:                                     $userallowed=1;
                   11735:                                     last;
                   11736:                                 }
                   11737:                             }
                   11738:                         }
                   11739:                     }
                   11740:                 }
                   11741:                 if ($slots{$slot}->{'allowedusers'}) {
                   11742:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11743:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11744:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11745:                         $userallowed = 1;
                   11746:                     }
                   11747:                 }
                   11748:                 next unless($userallowed);
                   11749:             }
                   11750:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11751:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11752:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11753:             my $uniqueperiod;
                   11754:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11755:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11756:             }
1.1040    raeburn  11757:             if (($startreserve < $now) &&
                   11758:                 (!$endreserve || $endreserve > $now)) {
                   11759:                 my $lastres = $endreserve;
                   11760:                 if (!$lastres) {
                   11761:                     $lastres = $slots{$slot}->{'starttime'};
                   11762:                 }
                   11763:                 $reservable_now{$slot} = {
                   11764:                                            symb       => $symb,
1.1250    raeburn  11765:                                            endreserve => $lastres,
                   11766:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11767:                                          };
                   11768:             } elsif (($startreserve > $now) &&
                   11769:                      (!$endreserve || $endreserve > $startreserve)) {
                   11770:                 $future_reservable{$slot} = {
                   11771:                                               symb         => $symb,
1.1250    raeburn  11772:                                               startreserve => $startreserve,
                   11773:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11774:                                             };
                   11775:             }
                   11776:         }
                   11777:     }
                   11778:     my @unsorted_reservable = keys(%reservable_now);
                   11779:     if (@unsorted_reservable > 0) {
                   11780:         @sorted_reservable = 
                   11781:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11782:     }
                   11783:     my @unsorted_future = keys(%future_reservable);
                   11784:     if (@unsorted_future > 0) {
                   11785:         @sorted_future =
                   11786:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11787:     }
                   11788:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11789: }
1.780     raeburn  11790: 
                   11791: =pod
                   11792: 
1.1057    foxr     11793: =back
                   11794: 
1.549     albertel 11795: =head1 HTTP Helpers
                   11796: 
                   11797: =over 4
                   11798: 
1.648     raeburn  11799: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11800: 
1.258     albertel 11801: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11802: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11803: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11804: 
                   11805: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11806: $possible_names is an ref to an array of form element names.  As an example:
                   11807: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11808: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11809: 
                   11810: =cut
1.1       albertel 11811: 
1.6       albertel 11812: sub get_unprocessed_cgi {
1.25      albertel 11813:   my ($query,$possible_names)= @_;
1.26      matthew  11814:   # $Apache::lonxml::debug=1;
1.356     albertel 11815:   foreach my $pair (split(/&/,$query)) {
                   11816:     my ($name, $value) = split(/=/,$pair);
1.369     www      11817:     $name = &unescape($name);
1.25      albertel 11818:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11819:       $value =~ tr/+/ /;
                   11820:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11821:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11822:     }
1.16      harris41 11823:   }
1.6       albertel 11824: }
                   11825: 
1.112     bowersj2 11826: =pod
                   11827: 
1.648     raeburn  11828: =item * &cacheheader() 
1.112     bowersj2 11829: 
                   11830: returns cache-controlling header code
                   11831: 
                   11832: =cut
                   11833: 
1.7       albertel 11834: sub cacheheader {
1.258     albertel 11835:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11836:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11837:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11838:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11839:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11840:     return $output;
1.7       albertel 11841: }
                   11842: 
1.112     bowersj2 11843: =pod
                   11844: 
1.648     raeburn  11845: =item * &no_cache($r) 
1.112     bowersj2 11846: 
                   11847: specifies header code to not have cache
                   11848: 
                   11849: =cut
                   11850: 
1.9       albertel 11851: sub no_cache {
1.216     albertel 11852:     my ($r) = @_;
                   11853:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11854: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11855:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11856:     $r->no_cache(1);
                   11857:     $r->header_out("Expires" => $date);
                   11858:     $r->header_out("Pragma" => "no-cache");
1.123     www      11859: }
                   11860: 
                   11861: sub content_type {
1.181     albertel 11862:     my ($r,$type,$charset) = @_;
1.299     foxr     11863:     if ($r) {
                   11864: 	#  Note that printout.pl calls this with undef for $r.
                   11865: 	&no_cache($r);
                   11866:     }
1.258     albertel 11867:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11868:     unless ($charset) {
                   11869: 	$charset=&Apache::lonlocal::current_encoding;
                   11870:     }
                   11871:     if ($charset) { $type.='; charset='.$charset; }
                   11872:     if ($r) {
                   11873: 	$r->content_type($type);
                   11874:     } else {
                   11875: 	print("Content-type: $type\n\n");
                   11876:     }
1.9       albertel 11877: }
1.25      albertel 11878: 
1.112     bowersj2 11879: =pod
                   11880: 
1.648     raeburn  11881: =item * &add_to_env($name,$value) 
1.112     bowersj2 11882: 
1.258     albertel 11883: adds $name to the %env hash with value
1.112     bowersj2 11884: $value, if $name already exists, the entry is converted to an array
                   11885: reference and $value is added to the array.
                   11886: 
                   11887: =cut
                   11888: 
1.25      albertel 11889: sub add_to_env {
                   11890:   my ($name,$value)=@_;
1.258     albertel 11891:   if (defined($env{$name})) {
                   11892:     if (ref($env{$name})) {
1.25      albertel 11893:       #already have multiple values
1.258     albertel 11894:       push(@{ $env{$name} },$value);
1.25      albertel 11895:     } else {
                   11896:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11897:       my $first=$env{$name};
                   11898:       undef($env{$name});
                   11899:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11900:     }
                   11901:   } else {
1.258     albertel 11902:     $env{$name}=$value;
1.25      albertel 11903:   }
1.31      albertel 11904: }
1.149     albertel 11905: 
                   11906: =pod
                   11907: 
1.648     raeburn  11908: =item * &get_env_multiple($name) 
1.149     albertel 11909: 
1.258     albertel 11910: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11911: values may be defined and end up as an array ref.
                   11912: 
                   11913: returns an array of values
                   11914: 
                   11915: =cut
                   11916: 
                   11917: sub get_env_multiple {
                   11918:     my ($name) = @_;
                   11919:     my @values;
1.258     albertel 11920:     if (defined($env{$name})) {
1.149     albertel 11921:         # exists is it an array
1.258     albertel 11922:         if (ref($env{$name})) {
                   11923:             @values=@{ $env{$name} };
1.149     albertel 11924:         } else {
1.258     albertel 11925:             $values[0]=$env{$name};
1.149     albertel 11926:         }
                   11927:     }
                   11928:     return(@values);
                   11929: }
                   11930: 
1.1249    damieng  11931: # Looks at given dependencies, and returns something depending on the context.
                   11932: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11933: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11934: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11935: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11936: # $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.
                   11937: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11938: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11939: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11940: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11941: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11942: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11943: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11944: # @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)
                   11945: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11946: sub ask_for_embedded_content {
1.1249    damieng  11947:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11948:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11949:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11950:         %currsubfile,%unused,$rem);
1.1071    raeburn  11951:     my $counter = 0;
                   11952:     my $numnew = 0;
1.987     raeburn  11953:     my $numremref = 0;
                   11954:     my $numinvalid = 0;
                   11955:     my $numpathchg = 0;
                   11956:     my $numexisting = 0;
1.1071    raeburn  11957:     my $numunused = 0;
                   11958:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11959:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11960:     my $heading = &mt('Upload embedded files');
                   11961:     my $buttontext = &mt('Upload');
                   11962: 
1.1249    damieng  11963:     # fills these variables based on the context:
                   11964:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11965:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11966:     if ($env{'request.course.id'}) {
1.1123    raeburn  11967:         if ($actionurl eq '/adm/dependencies') {
                   11968:             $navmap = Apache::lonnavmaps::navmap->new();
                   11969:         }
                   11970:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11971:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11972:     }
1.1123    raeburn  11973:     if (($actionurl eq '/adm/portfolio') || 
                   11974:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11975:         my $current_path='/';
                   11976:         if ($env{'form.currentpath'}) {
                   11977:             $current_path = $env{'form.currentpath'};
                   11978:         }
                   11979:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11980:             $udom = $cdom;
                   11981:             $uname = $cnum;
1.984     raeburn  11982:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11983:         } else {
                   11984:             $udom = $env{'user.domain'};
                   11985:             $uname = $env{'user.name'};
                   11986:             $url = '/userfiles/portfolio';
                   11987:         }
1.987     raeburn  11988:         $toplevel = $url.'/';
1.984     raeburn  11989:         $url .= $current_path;
                   11990:         $getpropath = 1;
1.987     raeburn  11991:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11992:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11993:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11994:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11995:         $toplevel = $url;
1.984     raeburn  11996:         if ($rest ne '') {
1.987     raeburn  11997:             $url .= $rest;
                   11998:         }
                   11999:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12000:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12001:             $url = $args->{'docs_url'};
                   12002:             $toplevel = $url;
1.1084    raeburn  12003:             if ($args->{'context'} eq 'paste') {
                   12004:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12005:                 ($path) = 
                   12006:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12007:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12008:                 $fileloc =~ s{^/}{};
                   12009:             }
1.1071    raeburn  12010:         }
1.1084    raeburn  12011:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12012:         if ($env{'request.course.id'} ne '') {
                   12013:             if (ref($args) eq 'HASH') {
                   12014:                 $url = $args->{'docs_url'};
                   12015:                 $title = $args->{'docs_title'};
1.1126    raeburn  12016:                 $toplevel = $url; 
                   12017:                 unless ($toplevel =~ m{^/}) {
                   12018:                     $toplevel = "/$url";
                   12019:                 }
1.1085    raeburn  12020:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12021:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12022:                     $path = $1;
                   12023:                 } else {
                   12024:                     ($path) =
                   12025:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12026:                 }
1.1195    raeburn  12027:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12028:                     $fileloc = $toplevel;
                   12029:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12030:                     my ($udom,$uname,$fname) =
                   12031:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12032:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12033:                 } else {
                   12034:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12035:                 }
1.1071    raeburn  12036:                 $fileloc =~ s{^/}{};
                   12037:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12038:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12039:             }
1.987     raeburn  12040:         }
1.1123    raeburn  12041:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12042:         $udom = $cdom;
                   12043:         $uname = $cnum;
                   12044:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12045:         $toplevel = $url;
                   12046:         $path = $url;
                   12047:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12048:         $fileloc =~ s{^/}{};
1.987     raeburn  12049:     }
1.1249    damieng  12050:     
                   12051:     # parses the dependency paths to get some info
                   12052:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12053:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12054:     # (will be completed later)
                   12055:     # $mapping:
                   12056:     #   for external URLs: external URL -> external URL
                   12057:     #   for relative paths: clean path -> original path
                   12058:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12059:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12060:     foreach my $file (keys(%{$allfiles})) {
                   12061:         my $embed_file;
                   12062:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12063:             $embed_file = $1;
                   12064:         } else {
                   12065:             $embed_file = $file;
                   12066:         }
1.1158    raeburn  12067:         my ($absolutepath,$cleaned_file);
                   12068:         if ($embed_file =~ m{^\w+://}) {
                   12069:             $cleaned_file = $embed_file;
1.1147    raeburn  12070:             $newfiles{$cleaned_file} = 1;
                   12071:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12072:         } else {
1.1158    raeburn  12073:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12074:             if ($embed_file =~ m{^/}) {
                   12075:                 $absolutepath = $embed_file;
                   12076:             }
1.1147    raeburn  12077:             if ($cleaned_file =~ m{/}) {
                   12078:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12079:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12080:                 my $item = $fname;
                   12081:                 if ($path ne '') {
                   12082:                     $item = $path.'/'.$fname;
                   12083:                     $subdependencies{$path}{$fname} = 1;
                   12084:                 } else {
                   12085:                     $dependencies{$item} = 1;
                   12086:                 }
                   12087:                 if ($absolutepath) {
                   12088:                     $mapping{$item} = $absolutepath;
                   12089:                 } else {
                   12090:                     $mapping{$item} = $embed_file;
                   12091:                 }
                   12092:             } else {
                   12093:                 $dependencies{$embed_file} = 1;
                   12094:                 if ($absolutepath) {
1.1147    raeburn  12095:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12096:                 } else {
1.1147    raeburn  12097:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12098:                 }
                   12099:             }
1.984     raeburn  12100:         }
                   12101:     }
1.1249    damieng  12102:     
                   12103:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12104:     # and lists
                   12105:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12106:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12107:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12108:     #                                    the path had to be cleaned up
                   12109:     # $existing: hash clean path -> 1 if the file exists
                   12110:     # $numexisting: number of keys in $existing
                   12111:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12112:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12113:     #                                      dependency subdirectories that are
                   12114:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12115:     my $dirptr = 16384;
1.984     raeburn  12116:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12117:         $currsubfile{$path} = {};
1.1123    raeburn  12118:         if (($actionurl eq '/adm/portfolio') || 
                   12119:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12120:             my ($sublistref,$listerror) =
                   12121:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12122:             if (ref($sublistref) eq 'ARRAY') {
                   12123:                 foreach my $line (@{$sublistref}) {
                   12124:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12125:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12126:                 }
1.984     raeburn  12127:             }
1.987     raeburn  12128:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12129:             if (opendir(my $dir,$url.'/'.$path)) {
                   12130:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12131:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12132:             }
1.1084    raeburn  12133:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12134:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12135:                   ($args->{'context'} eq 'paste')) ||
                   12136:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12137:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12138:                 my $dir;
                   12139:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12140:                     $dir = $fileloc;
                   12141:                 } else {
                   12142:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12143:                 }
1.1071    raeburn  12144:                 if ($dir ne '') {
                   12145:                     my ($sublistref,$listerror) =
                   12146:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12147:                     if (ref($sublistref) eq 'ARRAY') {
                   12148:                         foreach my $line (@{$sublistref}) {
                   12149:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12150:                                 undef,$mtime)=split(/\&/,$line,12);
                   12151:                             unless (($testdir&$dirptr) ||
                   12152:                                     ($file_name =~ /^\.\.?$/)) {
                   12153:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12154:                             }
                   12155:                         }
                   12156:                     }
                   12157:                 }
1.984     raeburn  12158:             }
                   12159:         }
                   12160:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12161:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12162:                 my $item = $path.'/'.$file;
                   12163:                 unless ($mapping{$item} eq $item) {
                   12164:                     $pathchanges{$item} = 1;
                   12165:                 }
                   12166:                 $existing{$item} = 1;
                   12167:                 $numexisting ++;
                   12168:             } else {
                   12169:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12170:             }
                   12171:         }
1.1071    raeburn  12172:         if ($actionurl eq '/adm/dependencies') {
                   12173:             foreach my $path (keys(%currsubfile)) {
                   12174:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12175:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12176:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12177:                              next if (($rem ne '') &&
                   12178:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12179:                                        (ref($navmap) &&
                   12180:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12181:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12182:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12183:                              $unused{$path.'/'.$file} = 1; 
                   12184:                          }
                   12185:                     }
                   12186:                 }
                   12187:             }
                   12188:         }
1.984     raeburn  12189:     }
1.1249    damieng  12190:     
                   12191:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12192:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12193:     my %currfile;
1.1123    raeburn  12194:     if (($actionurl eq '/adm/portfolio') ||
                   12195:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12196:         my ($dirlistref,$listerror) =
                   12197:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12198:         if (ref($dirlistref) eq 'ARRAY') {
                   12199:             foreach my $line (@{$dirlistref}) {
                   12200:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12201:                 $currfile{$file_name} = 1;
                   12202:             }
1.984     raeburn  12203:         }
1.987     raeburn  12204:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12205:         if (opendir(my $dir,$url)) {
1.987     raeburn  12206:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12207:             map {$currfile{$_} = 1;} @dir_list;
                   12208:         }
1.1084    raeburn  12209:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12210:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12211:               ($args->{'context'} eq 'paste')) ||
                   12212:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12213:         if ($env{'request.course.id'} ne '') {
                   12214:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12215:             if ($dir ne '') {
                   12216:                 my ($dirlistref,$listerror) =
                   12217:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12218:                 if (ref($dirlistref) eq 'ARRAY') {
                   12219:                     foreach my $line (@{$dirlistref}) {
                   12220:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12221:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12222:                         unless (($testdir&$dirptr) ||
                   12223:                                 ($file_name =~ /^\.\.?$/)) {
                   12224:                             $currfile{$file_name} = [$size,$mtime];
                   12225:                         }
                   12226:                     }
                   12227:                 }
                   12228:             }
                   12229:         }
1.984     raeburn  12230:     }
1.1249    damieng  12231:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12232:     # are not in subdirectories, using $currfile
1.984     raeburn  12233:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12234:         if (exists($currfile{$file})) {
1.987     raeburn  12235:             unless ($mapping{$file} eq $file) {
                   12236:                 $pathchanges{$file} = 1;
                   12237:             }
                   12238:             $existing{$file} = 1;
                   12239:             $numexisting ++;
                   12240:         } else {
1.984     raeburn  12241:             $newfiles{$file} = 1;
                   12242:         }
                   12243:     }
1.1071    raeburn  12244:     foreach my $file (keys(%currfile)) {
                   12245:         unless (($file eq $filename) ||
                   12246:                 ($file eq $filename.'.bak') ||
                   12247:                 ($dependencies{$file})) {
1.1085    raeburn  12248:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12249:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12250:                     next if (($rem ne '') &&
                   12251:                              (($env{"httpref.$rem".$file} ne '') ||
                   12252:                               (ref($navmap) &&
                   12253:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12254:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12255:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12256:                 }
1.1085    raeburn  12257:             }
1.1071    raeburn  12258:             $unused{$file} = 1;
                   12259:         }
                   12260:     }
1.1249    damieng  12261:     
                   12262:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12263:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12264:         ($args->{'context'} eq 'paste')) {
                   12265:         $counter = scalar(keys(%existing));
                   12266:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12267:         return ($output,$counter,$numpathchg,\%existing);
                   12268:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12269:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12270:         $counter = scalar(keys(%existing));
                   12271:         $numpathchg = scalar(keys(%pathchanges));
                   12272:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12273:     }
1.1249    damieng  12274:     
                   12275:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12276:     
                   12277:     # $upload_output: missing dependencies (with upload form)
                   12278:     # $modify_output: uploaded dependencies (in use)
                   12279:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12280:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12281:         if ($actionurl eq '/adm/dependencies') {
                   12282:             next if ($embed_file =~ m{^\w+://});
                   12283:         }
1.660     raeburn  12284:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12285:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12286:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12287:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12288:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12289:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12290:         }
1.1123    raeburn  12291:         $upload_output .= '</td>';
1.1071    raeburn  12292:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12293:             $upload_output.='<td align="right">'.
                   12294:                             '<span class="LC_info LC_fontsize_medium">'.
                   12295:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12296:             $numremref++;
1.660     raeburn  12297:         } elsif ($args->{'error_on_invalid_names'}
                   12298:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12299:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12300:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12301:             $numinvalid++;
1.660     raeburn  12302:         } else {
1.1123    raeburn  12303:             $upload_output .= '<td>'.
                   12304:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12305:                                                      $embed_file,\%mapping,
1.1071    raeburn  12306:                                                      $allfiles,$codebase,'upload');
                   12307:             $counter ++;
                   12308:             $numnew ++;
1.987     raeburn  12309:         }
                   12310:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12311:     }
                   12312:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12313:         if ($actionurl eq '/adm/dependencies') {
                   12314:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12315:             $modify_output .= &start_data_table_row().
                   12316:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12317:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12318:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12319:                               '<td>'.$size.'</td>'.
                   12320:                               '<td>'.$mtime.'</td>'.
                   12321:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12322:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12323:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12324:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12325:                               &embedded_file_element('upload_embedded',$counter,
                   12326:                                                      $embed_file,\%mapping,
                   12327:                                                      $allfiles,$codebase,'modify').
                   12328:                               '</div></td>'.
                   12329:                               &end_data_table_row()."\n";
                   12330:             $counter ++;
                   12331:         } else {
                   12332:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12333:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12334:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12335:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12336:                               &Apache::loncommon::end_data_table_row()."\n";
                   12337:         }
                   12338:     }
                   12339:     my $delidx = $counter;
                   12340:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12341:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12342:         $delete_output .= &start_data_table_row().
                   12343:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12344:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12345:                           '<td>'.$size.'</td>'.
                   12346:                           '<td>'.$mtime.'</td>'.
                   12347:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12348:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12349:                           &embedded_file_element('upload_embedded',$delidx,
                   12350:                                                  $oldfile,\%mapping,$allfiles,
                   12351:                                                  $codebase,'delete').'</td>'.
                   12352:                           &end_data_table_row()."\n"; 
                   12353:         $numunused ++;
                   12354:         $delidx ++;
1.987     raeburn  12355:     }
                   12356:     if ($upload_output) {
                   12357:         $upload_output = &start_data_table().
                   12358:                          $upload_output.
                   12359:                          &end_data_table()."\n";
                   12360:     }
1.1071    raeburn  12361:     if ($modify_output) {
                   12362:         $modify_output = &start_data_table().
                   12363:                          &start_data_table_header_row().
                   12364:                          '<th>'.&mt('File').'</th>'.
                   12365:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12366:                          '<th>'.&mt('Modified').'</th>'.
                   12367:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12368:                          &end_data_table_header_row().
                   12369:                          $modify_output.
                   12370:                          &end_data_table()."\n";
                   12371:     }
                   12372:     if ($delete_output) {
                   12373:         $delete_output = &start_data_table().
                   12374:                          &start_data_table_header_row().
                   12375:                          '<th>'.&mt('File').'</th>'.
                   12376:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12377:                          '<th>'.&mt('Modified').'</th>'.
                   12378:                          '<th>'.&mt('Delete?').'</th>'.
                   12379:                          &end_data_table_header_row().
                   12380:                          $delete_output.
                   12381:                          &end_data_table()."\n";
                   12382:     }
1.987     raeburn  12383:     my $applies = 0;
                   12384:     if ($numremref) {
                   12385:         $applies ++;
                   12386:     }
                   12387:     if ($numinvalid) {
                   12388:         $applies ++;
                   12389:     }
                   12390:     if ($numexisting) {
                   12391:         $applies ++;
                   12392:     }
1.1071    raeburn  12393:     if ($counter || $numunused) {
1.987     raeburn  12394:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12395:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12396:                   $state.'<h3>'.$heading.'</h3>'; 
                   12397:         if ($actionurl eq '/adm/dependencies') {
                   12398:             if ($numnew) {
                   12399:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12400:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12401:                            $upload_output.'<br />'."\n";
                   12402:             }
                   12403:             if ($numexisting) {
                   12404:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12405:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12406:                            $modify_output.'<br />'."\n";
                   12407:                            $buttontext = &mt('Save changes');
                   12408:             }
                   12409:             if ($numunused) {
                   12410:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12411:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12412:                            $delete_output.'<br />'."\n";
                   12413:                            $buttontext = &mt('Save changes');
                   12414:             }
                   12415:         } else {
                   12416:             $output .= $upload_output.'<br />'."\n";
                   12417:         }
                   12418:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12419:                    $counter.'" />'."\n";
                   12420:         if ($actionurl eq '/adm/dependencies') { 
                   12421:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12422:                        $numnew.'" />'."\n";
                   12423:         } elsif ($actionurl eq '') {
1.987     raeburn  12424:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12425:         }
                   12426:     } elsif ($applies) {
                   12427:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12428:         if ($applies > 1) {
                   12429:             $output .=  
1.1123    raeburn  12430:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12431:             if ($numremref) {
                   12432:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12433:             }
                   12434:             if ($numinvalid) {
                   12435:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12436:             }
                   12437:             if ($numexisting) {
                   12438:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12439:             }
                   12440:             $output .= '</ul><br />';
                   12441:         } elsif ($numremref) {
                   12442:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12443:         } elsif ($numinvalid) {
                   12444:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12445:         } elsif ($numexisting) {
                   12446:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12447:         }
                   12448:         $output .= $upload_output.'<br />';
                   12449:     }
                   12450:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12451:     $chgcount = $counter;
1.987     raeburn  12452:     if (keys(%pathchanges) > 0) {
                   12453:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12454:             if ($counter) {
1.987     raeburn  12455:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12456:                                                   $embed_file,\%mapping,
1.1071    raeburn  12457:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12458:             } else {
                   12459:                 $pathchange_output .= 
                   12460:                     &start_data_table_row().
                   12461:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12462:                     $chgcount.'" checked="checked" /></td>'.
                   12463:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12464:                     '<td>'.$embed_file.
                   12465:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12466:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12467:                     '</td>'.&end_data_table_row();
1.660     raeburn  12468:             }
1.987     raeburn  12469:             $numpathchg ++;
                   12470:             $chgcount ++;
1.660     raeburn  12471:         }
                   12472:     }
1.1127    raeburn  12473:     if (($counter) || ($numunused)) {
1.987     raeburn  12474:         if ($numpathchg) {
                   12475:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12476:                        $numpathchg.'" />'."\n";
                   12477:         }
                   12478:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12479:             ($actionurl eq '/adm/imsimport')) {
                   12480:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12481:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12482:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12483:         } elsif ($actionurl eq '/adm/dependencies') {
                   12484:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12485:         }
1.1123    raeburn  12486:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12487:     } elsif ($numpathchg) {
                   12488:         my %pathchange = ();
                   12489:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12490:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12491:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12492:         }
1.987     raeburn  12493:     }
1.1071    raeburn  12494:     return ($output,$counter,$numpathchg);
1.987     raeburn  12495: }
                   12496: 
1.1147    raeburn  12497: =pod
                   12498: 
                   12499: =item * clean_path($name)
                   12500: 
                   12501: Performs clean-up of directories, subdirectories and filename in an
                   12502: embedded object, referenced in an HTML file which is being uploaded
                   12503: to a course or portfolio, where 
                   12504: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12505: checked.
                   12506: 
                   12507: Clean-up is similar to replacements in lonnet::clean_filename()
                   12508: except each / between sub-directory and next level is preserved.
                   12509: 
                   12510: =cut
                   12511: 
                   12512: sub clean_path {
                   12513:     my ($embed_file) = @_;
                   12514:     $embed_file =~s{^/+}{};
                   12515:     my @contents;
                   12516:     if ($embed_file =~ m{/}) {
                   12517:         @contents = split(/\//,$embed_file);
                   12518:     } else {
                   12519:         @contents = ($embed_file);
                   12520:     }
                   12521:     my $lastidx = scalar(@contents)-1;
                   12522:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12523:         $contents[$i]=~s{\\}{/}g;
                   12524:         $contents[$i]=~s/\s+/\_/g;
                   12525:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12526:         if ($i == $lastidx) {
                   12527:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12528:         }
                   12529:     }
                   12530:     if ($lastidx > 0) {
                   12531:         return join('/',@contents);
                   12532:     } else {
                   12533:         return $contents[0];
                   12534:     }
                   12535: }
                   12536: 
1.987     raeburn  12537: sub embedded_file_element {
1.1071    raeburn  12538:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12539:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12540:                    (ref($codebase) eq 'HASH'));
                   12541:     my $output;
1.1071    raeburn  12542:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12543:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12544:     }
                   12545:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12546:                &escape($embed_file).'" />';
                   12547:     unless (($context eq 'upload_embedded') && 
                   12548:             ($mapping->{$embed_file} eq $embed_file)) {
                   12549:         $output .='
                   12550:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12551:     }
                   12552:     my $attrib;
                   12553:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12554:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12555:     }
                   12556:     $output .=
                   12557:         "\n\t\t".
                   12558:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12559:         $attrib.'" />';
                   12560:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12561:         $output .=
                   12562:             "\n\t\t".
                   12563:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12564:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12565:     }
1.987     raeburn  12566:     return $output;
1.660     raeburn  12567: }
                   12568: 
1.1071    raeburn  12569: sub get_dependency_details {
                   12570:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12571:     my ($size,$mtime,$showsize,$showmtime);
                   12572:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12573:         if ($embed_file =~ m{/}) {
                   12574:             my ($path,$fname) = split(/\//,$embed_file);
                   12575:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12576:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12577:             }
                   12578:         } else {
                   12579:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12580:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12581:             }
                   12582:         }
                   12583:         $showsize = $size/1024.0;
                   12584:         $showsize = sprintf("%.1f",$showsize);
                   12585:         if ($mtime > 0) {
                   12586:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12587:         }
                   12588:     }
                   12589:     return ($showsize,$showmtime);
                   12590: }
                   12591: 
                   12592: sub ask_embedded_js {
                   12593:     return <<"END";
                   12594: <script type="text/javascript"">
                   12595: // <![CDATA[
                   12596: function toggleBrowse(counter) {
                   12597:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12598:     var fileid = document.getElementById('embedded_item_'+counter);
                   12599:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12600:     if (chkboxid.checked == true) {
                   12601:         uploaddivid.style.display='block';
                   12602:     } else {
                   12603:         uploaddivid.style.display='none';
                   12604:         fileid.value = '';
                   12605:     }
                   12606: }
                   12607: // ]]>
                   12608: </script>
                   12609: 
                   12610: END
                   12611: }
                   12612: 
1.661     raeburn  12613: sub upload_embedded {
                   12614:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12615:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12616:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12617:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12618:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12619:         my $orig_uploaded_filename =
                   12620:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12621:         foreach my $type ('orig','ref','attrib','codebase') {
                   12622:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12623:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12624:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12625:             }
                   12626:         }
1.661     raeburn  12627:         my ($path,$fname) =
                   12628:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12629:         # no path, whole string is fname
                   12630:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12631:         $fname = &Apache::lonnet::clean_filename($fname);
                   12632:         # See if there is anything left
                   12633:         next if ($fname eq '');
                   12634: 
                   12635:         # Check if file already exists as a file or directory.
                   12636:         my ($state,$msg);
                   12637:         if ($context eq 'portfolio') {
                   12638:             my $port_path = $dirpath;
                   12639:             if ($group ne '') {
                   12640:                 $port_path = "groups/$group/$port_path";
                   12641:             }
1.987     raeburn  12642:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12643:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12644:                                               $dir_root,$port_path,$disk_quota,
                   12645:                                               $current_disk_usage,$uname,$udom);
                   12646:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12647:                 || $state eq 'file_locked') {
1.661     raeburn  12648:                 $output .= $msg;
                   12649:                 next;
                   12650:             }
                   12651:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12652:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12653:             if ($state eq 'exists') {
                   12654:                 $output .= $msg;
                   12655:                 next;
                   12656:             }
                   12657:         }
                   12658:         # Check if extension is valid
                   12659:         if (($fname =~ /\.(\w+)$/) &&
                   12660:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12661:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12662:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12663:             next;
                   12664:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12665:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12666:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12667:             next;
                   12668:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12669:             $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  12670:             next;
                   12671:         }
                   12672:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12673:         my $subdir = $path;
                   12674:         $subdir =~ s{/+$}{};
1.661     raeburn  12675:         if ($context eq 'portfolio') {
1.984     raeburn  12676:             my $result;
                   12677:             if ($state eq 'existingfile') {
                   12678:                 $result=
                   12679:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12680:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12681:             } else {
1.984     raeburn  12682:                 $result=
                   12683:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12684:                                                     $dirpath.
1.1123    raeburn  12685:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12686:                 if ($result !~ m|^/uploaded/|) {
                   12687:                     $output .= '<span class="LC_error">'
                   12688:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12689:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12690:                                .'</span><br />';
                   12691:                     next;
                   12692:                 } else {
1.987     raeburn  12693:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12694:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12695:                 }
1.661     raeburn  12696:             }
1.1123    raeburn  12697:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12698:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12699:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12700:             my $result =
1.1126    raeburn  12701:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12702:             if ($result !~ m|^/uploaded/|) {
                   12703:                 $output .= '<span class="LC_error">'
                   12704:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12705:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12706:                            .'</span><br />';
                   12707:                     next;
                   12708:             } else {
                   12709:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12710:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12711:                 if ($context eq 'syllabus') {
                   12712:                     &Apache::lonnet::make_public_indefinitely($result);
                   12713:                 }
1.987     raeburn  12714:             }
1.661     raeburn  12715:         } else {
                   12716: # Save the file
                   12717:             my $target = $env{'form.embedded_item_'.$i};
                   12718:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12719:             my $dest = $fullpath.$fname;
                   12720:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12721:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12722:             my $count;
                   12723:             my $filepath = $dir_root;
1.1027    raeburn  12724:             foreach my $subdir (@parts) {
                   12725:                 $filepath .= "/$subdir";
                   12726:                 if (!-e $filepath) {
1.661     raeburn  12727:                     mkdir($filepath,0770);
                   12728:                 }
                   12729:             }
                   12730:             my $fh;
                   12731:             if (!open($fh,'>'.$dest)) {
                   12732:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12733:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12734:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12735:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12736:                            '</span><br />';
                   12737:             } else {
                   12738:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12739:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12740:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12741:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12742:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12743:                               '</span><br />';
                   12744:                 } else {
1.987     raeburn  12745:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12746:                                $url.'</span>').'<br />';
                   12747:                     unless ($context eq 'testbank') {
                   12748:                         $footer .= &mt('View embedded file: [_1]',
                   12749:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12750:                     }
                   12751:                 }
                   12752:                 close($fh);
                   12753:             }
                   12754:         }
                   12755:         if ($env{'form.embedded_ref_'.$i}) {
                   12756:             $pathchange{$i} = 1;
                   12757:         }
                   12758:     }
                   12759:     if ($output) {
                   12760:         $output = '<p>'.$output.'</p>';
                   12761:     }
                   12762:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12763:     $returnflag = 'ok';
1.1071    raeburn  12764:     my $numpathchgs = scalar(keys(%pathchange));
                   12765:     if ($numpathchgs > 0) {
1.987     raeburn  12766:         if ($context eq 'portfolio') {
                   12767:             $output .= '<p>'.&mt('or').'</p>';
                   12768:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12769:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12770:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12771:             $returnflag = 'modify_orightml';
                   12772:         }
                   12773:     }
1.1071    raeburn  12774:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12775: }
                   12776: 
                   12777: sub modify_html_form {
                   12778:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12779:     my $end = 0;
                   12780:     my $modifyform;
                   12781:     if ($context eq 'upload_embedded') {
                   12782:         return unless (ref($pathchange) eq 'HASH');
                   12783:         if ($env{'form.number_embedded_items'}) {
                   12784:             $end += $env{'form.number_embedded_items'};
                   12785:         }
                   12786:         if ($env{'form.number_pathchange_items'}) {
                   12787:             $end += $env{'form.number_pathchange_items'};
                   12788:         }
                   12789:         if ($end) {
                   12790:             for (my $i=0; $i<$end; $i++) {
                   12791:                 if ($i < $env{'form.number_embedded_items'}) {
                   12792:                     next unless($pathchange->{$i});
                   12793:                 }
                   12794:                 $modifyform .=
                   12795:                     &start_data_table_row().
                   12796:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12797:                     'checked="checked" /></td>'.
                   12798:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12799:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12800:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12801:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12802:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12803:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12804:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12805:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12806:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12807:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12808:                     &end_data_table_row();
1.1071    raeburn  12809:             }
1.987     raeburn  12810:         }
                   12811:     } else {
                   12812:         $modifyform = $pathchgtable;
                   12813:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12814:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12815:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12816:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12817:         }
                   12818:     }
                   12819:     if ($modifyform) {
1.1071    raeburn  12820:         if ($actionurl eq '/adm/dependencies') {
                   12821:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12822:         }
1.987     raeburn  12823:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12824:                '<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".
                   12825:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12826:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12827:                '</ol></p>'."\n".'<p>'.
                   12828:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12829:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12830:                &start_data_table()."\n".
                   12831:                &start_data_table_header_row().
                   12832:                '<th>'.&mt('Change?').'</th>'.
                   12833:                '<th>'.&mt('Current reference').'</th>'.
                   12834:                '<th>'.&mt('Required reference').'</th>'.
                   12835:                &end_data_table_header_row()."\n".
                   12836:                $modifyform.
                   12837:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12838:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12839:                '</form>'."\n";
                   12840:     }
                   12841:     return;
                   12842: }
                   12843: 
                   12844: sub modify_html_refs {
1.1123    raeburn  12845:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12846:     my $container;
                   12847:     if ($context eq 'portfolio') {
                   12848:         $container = $env{'form.container'};
                   12849:     } elsif ($context eq 'coursedoc') {
                   12850:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12851:     } elsif ($context eq 'manage_dependencies') {
                   12852:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12853:         $container = "/$container";
1.1123    raeburn  12854:     } elsif ($context eq 'syllabus') {
                   12855:         $container = $url;
1.987     raeburn  12856:     } else {
1.1027    raeburn  12857:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12858:     }
                   12859:     my (%allfiles,%codebase,$output,$content);
                   12860:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12861:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12862:         if (wantarray) {
                   12863:             return ('',0,0); 
                   12864:         } else {
                   12865:             return;
                   12866:         }
                   12867:     }
                   12868:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12869:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12870:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12871:             if (wantarray) {
                   12872:                 return ('',0,0);
                   12873:             } else {
                   12874:                 return;
                   12875:             }
                   12876:         } 
1.987     raeburn  12877:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12878:         if ($content eq '-1') {
                   12879:             if (wantarray) {
                   12880:                 return ('',0,0);
                   12881:             } else {
                   12882:                 return;
                   12883:             }
                   12884:         }
1.987     raeburn  12885:     } else {
1.1071    raeburn  12886:         unless ($container =~ /^\Q$dir_root\E/) {
                   12887:             if (wantarray) {
                   12888:                 return ('',0,0);
                   12889:             } else {
                   12890:                 return;
                   12891:             }
                   12892:         } 
1.1317    raeburn  12893:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12894:             $content = join('', <$fh>);
                   12895:             close($fh);
                   12896:         } else {
1.1071    raeburn  12897:             if (wantarray) {
                   12898:                 return ('',0,0);
                   12899:             } else {
                   12900:                 return;
                   12901:             }
1.987     raeburn  12902:         }
                   12903:     }
                   12904:     my ($count,$codebasecount) = (0,0);
                   12905:     my $mm = new File::MMagic;
                   12906:     my $mime_type = $mm->checktype_contents($content);
                   12907:     if ($mime_type eq 'text/html') {
                   12908:         my $parse_result = 
                   12909:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12910:                                                     \%codebase,\$content);
                   12911:         if ($parse_result eq 'ok') {
                   12912:             foreach my $i (@changes) {
                   12913:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12914:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12915:                 if ($allfiles{$ref}) {
                   12916:                     my $newname =  $orig;
                   12917:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12918:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12919:                     if ($attrib_regexp =~ /:/) {
                   12920:                         $attrib_regexp =~ s/\:/|/g;
                   12921:                     }
                   12922:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12923:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12924:                         $count += $numchg;
1.1123    raeburn  12925:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12926:                         delete($allfiles{$ref});
1.987     raeburn  12927:                     }
                   12928:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12929:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12930:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12931:                         $codebasecount ++;
                   12932:                     }
                   12933:                 }
                   12934:             }
1.1123    raeburn  12935:             my $skiprewrites;
1.987     raeburn  12936:             if ($count || $codebasecount) {
                   12937:                 my $saveresult;
1.1071    raeburn  12938:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12939:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12940:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12941:                     if ($url eq $container) {
                   12942:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12943:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12944:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12945:                                             $fname.'</span>').'</p>';
1.987     raeburn  12946:                     } else {
                   12947:                          $output = '<p class="LC_error">'.
                   12948:                                    &mt('Error: update failed for: [_1].',
                   12949:                                    '<span class="LC_filename">'.
                   12950:                                    $container.'</span>').'</p>';
                   12951:                     }
1.1123    raeburn  12952:                     if ($context eq 'syllabus') {
                   12953:                         unless ($saveresult eq 'ok') {
                   12954:                             $skiprewrites = 1;
                   12955:                         }
                   12956:                     }
1.987     raeburn  12957:                 } else {
1.1317    raeburn  12958:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12959:                         print $fh $content;
                   12960:                         close($fh);
                   12961:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12962:                                   $count,'<span class="LC_filename">'.
                   12963:                                   $container.'</span>').'</p>';
1.661     raeburn  12964:                     } else {
1.987     raeburn  12965:                          $output = '<p class="LC_error">'.
                   12966:                                    &mt('Error: could not update [_1].',
                   12967:                                    '<span class="LC_filename">'.
                   12968:                                    $container.'</span>').'</p>';
1.661     raeburn  12969:                     }
                   12970:                 }
                   12971:             }
1.1123    raeburn  12972:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12973:                 my ($actionurl,$state);
                   12974:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12975:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12976:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12977:                                               \%codebase,
                   12978:                                               {'context' => 'rewrites',
                   12979:                                                'ignore_remote_references' => 1,});
                   12980:                 if (ref($mapping) eq 'HASH') {
                   12981:                     my $rewrites = 0;
                   12982:                     foreach my $key (keys(%{$mapping})) {
                   12983:                         next if ($key =~ m{^https?://});
                   12984:                         my $ref = $mapping->{$key};
                   12985:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12986:                         my $attrib;
                   12987:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12988:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12989:                         }
                   12990:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12991:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12992:                             $rewrites += $numchg;
                   12993:                         }
                   12994:                     }
                   12995:                     if ($rewrites) {
                   12996:                         my $saveresult; 
                   12997:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12998:                         if ($url eq $container) {
                   12999:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13000:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13001:                                             $count,'<span class="LC_filename">'.
                   13002:                                             $fname.'</span>').'</p>';
                   13003:                         } else {
                   13004:                             $output .= '<p class="LC_error">'.
                   13005:                                        &mt('Error: could not update links in [_1].',
                   13006:                                        '<span class="LC_filename">'.
                   13007:                                        $container.'</span>').'</p>';
                   13008: 
                   13009:                         }
                   13010:                     }
                   13011:                 }
                   13012:             }
1.987     raeburn  13013:         } else {
                   13014:             &logthis('Failed to parse '.$container.
                   13015:                      ' to modify references: '.$parse_result);
1.661     raeburn  13016:         }
                   13017:     }
1.1071    raeburn  13018:     if (wantarray) {
                   13019:         return ($output,$count,$codebasecount);
                   13020:     } else {
                   13021:         return $output;
                   13022:     }
1.661     raeburn  13023: }
                   13024: 
                   13025: sub check_for_existing {
                   13026:     my ($path,$fname,$element) = @_;
                   13027:     my ($state,$msg);
                   13028:     if (-d $path.'/'.$fname) {
                   13029:         $state = 'exists';
                   13030:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13031:     } elsif (-e $path.'/'.$fname) {
                   13032:         $state = 'exists';
                   13033:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13034:     }
                   13035:     if ($state eq 'exists') {
                   13036:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13037:     }
                   13038:     return ($state,$msg);
                   13039: }
                   13040: 
                   13041: sub check_for_upload {
                   13042:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13043:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13044:     my $filesize = length($env{'form.'.$element});
                   13045:     if (!$filesize) {
                   13046:         my $msg = '<span class="LC_error">'.
                   13047:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13048:                       '<span class="LC_filename">'.$fname.'</span>',
                   13049:                       $filesize).'<br />'.
1.1007    raeburn  13050:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13051:                   '</span>';
                   13052:         return ('zero_bytes',$msg);
                   13053:     }
                   13054:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13055:     my $getpropath = 1;
1.1021    raeburn  13056:     my ($dirlistref,$listerror) =
                   13057:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13058:     my $found_file = 0;
                   13059:     my $locked_file = 0;
1.991     raeburn  13060:     my @lockers;
                   13061:     my $navmap;
                   13062:     if ($env{'request.course.id'}) {
                   13063:         $navmap = Apache::lonnavmaps::navmap->new();
                   13064:     }
1.1021    raeburn  13065:     if (ref($dirlistref) eq 'ARRAY') {
                   13066:         foreach my $line (@{$dirlistref}) {
                   13067:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13068:             if ($file_name eq $fname){
                   13069:                 $file_name = $path.$file_name;
                   13070:                 if ($group ne '') {
                   13071:                     $file_name = $group.$file_name;
                   13072:                 }
                   13073:                 $found_file = 1;
                   13074:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13075:                     foreach my $lock (@lockers) {
                   13076:                         if (ref($lock) eq 'ARRAY') {
                   13077:                             my ($symb,$crsid) = @{$lock};
                   13078:                             if ($crsid eq $env{'request.course.id'}) {
                   13079:                                 if (ref($navmap)) {
                   13080:                                     my $res = $navmap->getBySymb($symb);
                   13081:                                     foreach my $part (@{$res->parts()}) { 
                   13082:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13083:                                         unless (($slot_status == $res->RESERVED) ||
                   13084:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13085:                                             $locked_file = 1;
                   13086:                                         }
1.991     raeburn  13087:                                     }
1.1021    raeburn  13088:                                 } else {
                   13089:                                     $locked_file = 1;
1.991     raeburn  13090:                                 }
                   13091:                             } else {
                   13092:                                 $locked_file = 1;
                   13093:                             }
                   13094:                         }
1.1021    raeburn  13095:                    }
                   13096:                 } else {
                   13097:                     my @info = split(/\&/,$rest);
                   13098:                     my $currsize = $info[6]/1000;
                   13099:                     if ($currsize < $filesize) {
                   13100:                         my $extra = $filesize - $currsize;
                   13101:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13102:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13103:                                       &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   13104:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13105:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13106:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13107:                             return ('will_exceed_quota',$msg);
                   13108:                         }
1.984     raeburn  13109:                     }
                   13110:                 }
1.661     raeburn  13111:             }
                   13112:         }
                   13113:     }
                   13114:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13115:         my $msg = '<p class="LC_warning">'.
                   13116:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13117:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13118:         return ('will_exceed_quota',$msg);
                   13119:     } elsif ($found_file) {
                   13120:         if ($locked_file) {
1.1179    bisitz   13121:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13122:             $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   13123:             $msg .= '</p>';
1.661     raeburn  13124:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13125:             return ('file_locked',$msg);
                   13126:         } else {
1.1179    bisitz   13127:             my $msg = '<p class="LC_error">';
1.984     raeburn  13128:             $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   13129:             $msg .= '</p>';
1.984     raeburn  13130:             return ('existingfile',$msg);
1.661     raeburn  13131:         }
                   13132:     }
                   13133: }
                   13134: 
1.987     raeburn  13135: sub check_for_traversal {
                   13136:     my ($path,$url,$toplevel) = @_;
                   13137:     my @parts=split(/\//,$path);
                   13138:     my $cleanpath;
                   13139:     my $fullpath = $url;
                   13140:     for (my $i=0;$i<@parts;$i++) {
                   13141:         next if ($parts[$i] eq '.');
                   13142:         if ($parts[$i] eq '..') {
                   13143:             $fullpath =~ s{([^/]+/)$}{};
                   13144:         } else {
                   13145:             $fullpath .= $parts[$i].'/';
                   13146:         }
                   13147:     }
                   13148:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13149:         $cleanpath = $1;
                   13150:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13151:         my $curr_toprel = $1;
                   13152:         my @parts = split(/\//,$curr_toprel);
                   13153:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13154:         my @urlparts = split(/\//,$url_toprel);
                   13155:         my $doubledots;
                   13156:         my $startdiff = -1;
                   13157:         for (my $i=0; $i<@urlparts; $i++) {
                   13158:             if ($startdiff == -1) {
                   13159:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13160:                     $startdiff = $i;
                   13161:                     $doubledots .= '../';
                   13162:                 }
                   13163:             } else {
                   13164:                 $doubledots .= '../';
                   13165:             }
                   13166:         }
                   13167:         if ($startdiff > -1) {
                   13168:             $cleanpath = $doubledots;
                   13169:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13170:                 $cleanpath .= $parts[$i].'/';
                   13171:             }
                   13172:         }
                   13173:     }
                   13174:     $cleanpath =~ s{(/)$}{};
                   13175:     return $cleanpath;
                   13176: }
1.31      albertel 13177: 
1.1053    raeburn  13178: sub is_archive_file {
                   13179:     my ($mimetype) = @_;
                   13180:     if (($mimetype eq 'application/octet-stream') ||
                   13181:         ($mimetype eq 'application/x-stuffit') ||
                   13182:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13183:         return 1;
                   13184:     }
                   13185:     return;
                   13186: }
                   13187: 
                   13188: sub decompress_form {
1.1065    raeburn  13189:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13190:     my %lt = &Apache::lonlocal::texthash (
                   13191:         this => 'This file is an archive file.',
1.1067    raeburn  13192:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13193:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13194:         youm => 'You may wish to extract its contents.',
                   13195:         extr => 'Extract contents',
1.1067    raeburn  13196:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13197:         proa => 'Process automatically?',
1.1053    raeburn  13198:         yes  => 'Yes',
                   13199:         no   => 'No',
1.1067    raeburn  13200:         fold => 'Title for folder containing movie',
                   13201:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13202:     );
1.1065    raeburn  13203:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13204:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13205:     my $info = &list_archive_contents($fileloc,\@paths);
                   13206:     if (@paths) {
                   13207:         foreach my $path (@paths) {
                   13208:             $path =~ s{^/}{};
1.1067    raeburn  13209:             if ($path =~ m{^([^/]+)/$}) {
                   13210:                 $topdir = $1;
                   13211:             }
1.1065    raeburn  13212:             if ($path =~ m{^([^/]+)/}) {
                   13213:                 $toplevel{$1} = $path;
                   13214:             } else {
                   13215:                 $toplevel{$path} = $path;
                   13216:             }
                   13217:         }
                   13218:     }
1.1067    raeburn  13219:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13220:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13221:                         "$topdir/media/",
                   13222:                         "$topdir/media/$topdir.mp4",
                   13223:                         "$topdir/media/FirstFrame.png",
                   13224:                         "$topdir/media/player.swf",
                   13225:                         "$topdir/media/swfobject.js",
                   13226:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13227:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13228:                          "$topdir/$topdir.mp4",
                   13229:                          "$topdir/$topdir\_config.xml",
                   13230:                          "$topdir/$topdir\_controller.swf",
                   13231:                          "$topdir/$topdir\_embed.css",
                   13232:                          "$topdir/$topdir\_First_Frame.png",
                   13233:                          "$topdir/$topdir\_player.html",
                   13234:                          "$topdir/$topdir\_Thumbnails.png",
                   13235:                          "$topdir/playerProductInstall.swf",
                   13236:                          "$topdir/scripts/",
                   13237:                          "$topdir/scripts/config_xml.js",
                   13238:                          "$topdir/scripts/handlebars.js",
                   13239:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13240:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13241:                          "$topdir/scripts/modernizr.js",
                   13242:                          "$topdir/scripts/player-min.js",
                   13243:                          "$topdir/scripts/swfobject.js",
                   13244:                          "$topdir/skins/",
                   13245:                          "$topdir/skins/configuration_express.xml",
                   13246:                          "$topdir/skins/express_show/",
                   13247:                          "$topdir/skins/express_show/player-min.css",
                   13248:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13249:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13250:                          "$topdir/$topdir.mp4",
                   13251:                          "$topdir/$topdir\_config.xml",
                   13252:                          "$topdir/$topdir\_controller.swf",
                   13253:                          "$topdir/$topdir\_embed.css",
                   13254:                          "$topdir/$topdir\_First_Frame.png",
                   13255:                          "$topdir/$topdir\_player.html",
                   13256:                          "$topdir/$topdir\_Thumbnails.png",
                   13257:                          "$topdir/playerProductInstall.swf",
                   13258:                          "$topdir/scripts/",
                   13259:                          "$topdir/scripts/config_xml.js",
                   13260:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13261:                          "$topdir/skins/",
                   13262:                          "$topdir/skins/configuration_express.xml",
                   13263:                          "$topdir/skins/express_show/",
                   13264:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13265:                          "$topdir/skins/express_show/spritesheet.png",
                   13266:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13267:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13268:         if (@diffs == 0) {
1.1164    raeburn  13269:             $is_camtasia = 6;
                   13270:         } else {
1.1197    raeburn  13271:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13272:             if (@diffs == 0) {
                   13273:                 $is_camtasia = 8;
1.1197    raeburn  13274:             } else {
                   13275:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13276:                 if (@diffs == 0) {
                   13277:                     $is_camtasia = 8;
                   13278:                 }
1.1164    raeburn  13279:             }
1.1067    raeburn  13280:         }
                   13281:     }
                   13282:     my $output;
                   13283:     if ($is_camtasia) {
                   13284:         $output = <<"ENDCAM";
                   13285: <script type="text/javascript" language="Javascript">
                   13286: // <![CDATA[
                   13287: 
                   13288: function camtasiaToggle() {
                   13289:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13290:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13291:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13292:                 document.getElementById('camtasia_titles').style.display='block';
                   13293:             } else {
                   13294:                 document.getElementById('camtasia_titles').style.display='none';
                   13295:             }
                   13296:         }
                   13297:     }
                   13298:     return;
                   13299: }
                   13300: 
                   13301: // ]]>
                   13302: </script>
                   13303: <p>$lt{'camt'}</p>
                   13304: ENDCAM
1.1065    raeburn  13305:     } else {
1.1067    raeburn  13306:         $output = '<p>'.$lt{'this'};
                   13307:         if ($info eq '') {
                   13308:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13309:         } else {
                   13310:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13311:                        '<div><pre>'.$info.'</pre></div>';
                   13312:         }
1.1065    raeburn  13313:     }
1.1067    raeburn  13314:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13315:     my $duplicates;
                   13316:     my $num = 0;
                   13317:     if (ref($dirlist) eq 'ARRAY') {
                   13318:         foreach my $item (@{$dirlist}) {
                   13319:             if (ref($item) eq 'ARRAY') {
                   13320:                 if (exists($toplevel{$item->[0]})) {
                   13321:                     $duplicates .= 
                   13322:                         &start_data_table_row().
                   13323:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13324:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13325:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13326:                         'value="1" />'.&mt('Yes').'</label>'.
                   13327:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13328:                         '<td>'.$item->[0].'</td>';
                   13329:                     if ($item->[2]) {
                   13330:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13331:                     } else {
                   13332:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13333:                     }
                   13334:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13335:                                    '<td>'.
                   13336:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13337:                                    '</td>'.
                   13338:                                    &end_data_table_row();
                   13339:                     $num ++;
                   13340:                 }
                   13341:             }
                   13342:         }
                   13343:     }
                   13344:     my $itemcount;
                   13345:     if (@paths > 0) {
                   13346:         $itemcount = scalar(@paths);
                   13347:     } else {
                   13348:         $itemcount = 1;
                   13349:     }
1.1067    raeburn  13350:     if ($is_camtasia) {
                   13351:         $output .= $lt{'auto'}.'<br />'.
                   13352:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13353:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13354:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13355:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13356:                    $lt{'no'}.'</label></span><br />'.
                   13357:                    '<div id="camtasia_titles" style="display:block">'.
                   13358:                    &Apache::lonhtmlcommon::start_pick_box().
                   13359:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13360:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13361:                    &Apache::lonhtmlcommon::row_closure().
                   13362:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13363:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13364:                    &Apache::lonhtmlcommon::row_closure(1).
                   13365:                    &Apache::lonhtmlcommon::end_pick_box().
                   13366:                    '</div>';
                   13367:     }
1.1065    raeburn  13368:     $output .= 
                   13369:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13370:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13371:         "\n";
1.1065    raeburn  13372:     if ($duplicates ne '') {
                   13373:         $output .= '<p><span class="LC_warning">'.
                   13374:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13375:                    &start_data_table().
                   13376:                    &start_data_table_header_row().
                   13377:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13378:                    '<th>'.&mt('Name').'</th>'.
                   13379:                    '<th>'.&mt('Type').'</th>'.
                   13380:                    '<th>'.&mt('Size').'</th>'.
                   13381:                    '<th>'.&mt('Last modified').'</th>'.
                   13382:                    &end_data_table_header_row().
                   13383:                    $duplicates.
                   13384:                    &end_data_table().
                   13385:                    '</p>';
                   13386:     }
1.1067    raeburn  13387:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13388:     if (ref($hiddenelements) eq 'HASH') {
                   13389:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13390:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13391:         }
                   13392:     }
                   13393:     $output .= <<"END";
1.1067    raeburn  13394: <br />
1.1053    raeburn  13395: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13396: </form>
                   13397: $noextract
                   13398: END
                   13399:     return $output;
                   13400: }
                   13401: 
1.1065    raeburn  13402: sub decompression_utility {
                   13403:     my ($program) = @_;
                   13404:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13405:     my $location;
                   13406:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13407:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13408:                          '/usr/sbin/') {
                   13409:             if (-x $dir.$program) {
                   13410:                 $location = $dir.$program;
                   13411:                 last;
                   13412:             }
                   13413:         }
                   13414:     }
                   13415:     return $location;
                   13416: }
                   13417: 
                   13418: sub list_archive_contents {
                   13419:     my ($file,$pathsref) = @_;
                   13420:     my (@cmd,$output);
                   13421:     my $needsregexp;
                   13422:     if ($file =~ /\.zip$/) {
                   13423:         @cmd = (&decompression_utility('unzip'),"-l");
                   13424:         $needsregexp = 1;
                   13425:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13426:              ($file =~ /\.tgz$/)) {
                   13427:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13428:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13429:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13430:     } elsif ($file =~ m|\.tar$|) {
                   13431:         @cmd = (&decompression_utility('tar'),"-tf");
                   13432:     }
                   13433:     if (@cmd) {
                   13434:         undef($!);
                   13435:         undef($@);
                   13436:         if (open(my $fh,"-|", @cmd, $file)) {
                   13437:             while (my $line = <$fh>) {
                   13438:                 $output .= $line;
                   13439:                 chomp($line);
                   13440:                 my $item;
                   13441:                 if ($needsregexp) {
                   13442:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13443:                 } else {
                   13444:                     $item = $line;
                   13445:                 }
                   13446:                 if ($item ne '') {
                   13447:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13448:                         push(@{$pathsref},$item);
                   13449:                     } 
                   13450:                 }
                   13451:             }
                   13452:             close($fh);
                   13453:         }
                   13454:     }
                   13455:     return $output;
                   13456: }
                   13457: 
1.1053    raeburn  13458: sub decompress_uploaded_file {
                   13459:     my ($file,$dir) = @_;
                   13460:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13461:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13462:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13463:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13464:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13465:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13466:     my $decompressed = $env{'cgi.decompressed'};
                   13467:     &Apache::lonnet::delenv('cgi.file');
                   13468:     &Apache::lonnet::delenv('cgi.dir');
                   13469:     &Apache::lonnet::delenv('cgi.decompressed');
                   13470:     return ($decompressed,$result);
                   13471: }
                   13472: 
1.1055    raeburn  13473: sub process_decompression {
                   13474:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13475:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13476:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13477:                &mt('Unexpected file path.').'</p>'."\n";
                   13478:     }
                   13479:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13480:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13481:                &mt('Unexpected course context.').'</p>'."\n";
                   13482:     }
1.1293    raeburn  13483:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13484:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13485:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13486:     }
1.1055    raeburn  13487:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13488:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13489:         $error = &mt('Filename not a supported archive file type.').
                   13490:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13491:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13492:     } else {
                   13493:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13494:         if ($docuhome eq 'no_host') {
                   13495:             $error = &mt('Could not determine home server for course.');
                   13496:         } else {
                   13497:             my @ids=&Apache::lonnet::current_machine_ids();
                   13498:             my $currdir = "$dir_root/$destination";
                   13499:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13500:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13501:                        "$dir_root/$destination";
                   13502:             } else {
                   13503:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13504:                        "$dir_root/$docudom/$docuname/$destination";
                   13505:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13506:                     $error = &mt('Archive file not found.');
                   13507:                 }
                   13508:             }
1.1065    raeburn  13509:             my (@to_overwrite,@to_skip);
                   13510:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13511:                 my $total = $env{'form.archive_overwrite_total'};
                   13512:                 for (my $i=0; $i<$total; $i++) {
                   13513:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13514:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13515:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13516:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13517:                     }
                   13518:                 }
                   13519:             }
                   13520:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13521:             my $numoverwrite = scalar(@to_overwrite);
                   13522:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13523:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13524:             } elsif ($dir eq '') {
1.1055    raeburn  13525:                 $error = &mt('Directory containing archive file unavailable.');
                   13526:             } elsif (!$error) {
1.1065    raeburn  13527:                 my ($decompressed,$display);
1.1292    raeburn  13528:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13529:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13530:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13531:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13532:                         ($decompressed,$display) = 
                   13533:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13534:                         foreach my $item (@to_skip) {
                   13535:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13536:                                 if (-f "$dir/$tempdir/$item") { 
                   13537:                                     unlink("$dir/$tempdir/$item");
                   13538:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13539:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13540:                                 }
                   13541:                             }
                   13542:                         }
                   13543:                         foreach my $item (@to_overwrite) {
                   13544:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13545:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13546:                                     if (-f "$dir/$item") {
                   13547:                                         unlink("$dir/$item");
                   13548:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13549:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13550:                                     }
                   13551:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13552:                                 }
1.1065    raeburn  13553:                             }
                   13554:                         }
1.1292    raeburn  13555:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13556:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13557:                         }
1.1065    raeburn  13558:                     }
                   13559:                 } else {
                   13560:                     ($decompressed,$display) = 
                   13561:                         &decompress_uploaded_file($file,$dir);
                   13562:                 }
1.1055    raeburn  13563:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13564:                     $output = '<p class="LC_info">'.
                   13565:                               &mt('Files extracted successfully from archive.').
                   13566:                               '</p>'."\n";
1.1055    raeburn  13567:                     my ($warning,$result,@contents);
                   13568:                     my ($newdirlistref,$newlisterror) =
                   13569:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13570:                                                  $docuname,1);
                   13571:                     my (%is_dir,%changes,@newitems);
                   13572:                     my $dirptr = 16384;
1.1065    raeburn  13573:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13574:                         foreach my $dir_line (@{$newdirlistref}) {
                   13575:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13576:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13577:                                 push(@newitems,$item);
                   13578:                                 if ($dirptr&$testdir) {
                   13579:                                     $is_dir{$item} = 1;
                   13580:                                 }
                   13581:                                 $changes{$item} = 1;
                   13582:                             }
                   13583:                         }
                   13584:                     }
                   13585:                     if (keys(%changes) > 0) {
                   13586:                         foreach my $item (sort(@newitems)) {
                   13587:                             if ($changes{$item}) {
                   13588:                                 push(@contents,$item);
                   13589:                             }
                   13590:                         }
                   13591:                     }
                   13592:                     if (@contents > 0) {
1.1067    raeburn  13593:                         my $wantform;
                   13594:                         unless ($env{'form.autoextract_camtasia'}) {
                   13595:                             $wantform = 1;
                   13596:                         }
1.1056    raeburn  13597:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13598:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13599:                                                                 $currdir,\%is_dir,
                   13600:                                                                 \%children,\%parent,
1.1056    raeburn  13601:                                                                 \@contents,\%dirorder,
                   13602:                                                                 \%titles,$wantform);
1.1055    raeburn  13603:                         if ($datatable ne '') {
                   13604:                             $output .= &archive_options_form('decompressed',$datatable,
                   13605:                                                              $count,$hiddenelem);
1.1065    raeburn  13606:                             my $startcount = 6;
1.1055    raeburn  13607:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13608:                                                            \%titles,\%children);
1.1055    raeburn  13609:                         }
1.1067    raeburn  13610:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13611:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13612:                             my %displayed;
                   13613:                             my $total = 1;
                   13614:                             $env{'form.archive_directory'} = [];
                   13615:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13616:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13617:                                 $path =~ s{/$}{};
                   13618:                                 my $item;
                   13619:                                 if ($path ne '') {
                   13620:                                     $item = "$path/$titles{$i}";
                   13621:                                 } else {
                   13622:                                     $item = $titles{$i};
                   13623:                                 }
                   13624:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13625:                                 if ($item eq $contents[0]) {
                   13626:                                     push(@{$env{'form.archive_directory'}},$i);
                   13627:                                     $env{'form.archive_'.$i} = 'display';
                   13628:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13629:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13630:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13631:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13632:                                     $env{'form.archive_'.$i} = 'display';
                   13633:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13634:                                     $displayed{'web'} = $i;
                   13635:                                 } else {
1.1164    raeburn  13636:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13637:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13638:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13639:                                         push(@{$env{'form.archive_directory'}},$i);
                   13640:                                     }
                   13641:                                     $env{'form.archive_'.$i} = 'dependency';
                   13642:                                 }
                   13643:                                 $total ++;
                   13644:                             }
                   13645:                             for (my $i=1; $i<$total; $i++) {
                   13646:                                 next if ($i == $displayed{'web'});
                   13647:                                 next if ($i == $displayed{'folder'});
                   13648:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13649:                             }
                   13650:                             $env{'form.phase'} = 'decompress_cleanup';
                   13651:                             $env{'form.archivedelete'} = 1;
                   13652:                             $env{'form.archive_count'} = $total-1;
                   13653:                             $output .=
                   13654:                                 &process_extracted_files('coursedocs',$docudom,
                   13655:                                                          $docuname,$destination,
                   13656:                                                          $dir_root,$hiddenelem);
                   13657:                         }
1.1055    raeburn  13658:                     } else {
                   13659:                         $warning = &mt('No new items extracted from archive file.');
                   13660:                     }
                   13661:                 } else {
                   13662:                     $output = $display;
                   13663:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13664:                 }
                   13665:             }
                   13666:         }
                   13667:     }
                   13668:     if ($error) {
                   13669:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13670:                    $error.'</p>'."\n";
                   13671:     }
                   13672:     if ($warning) {
                   13673:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13674:     }
                   13675:     return $output;
                   13676: }
                   13677: 
                   13678: sub get_extracted {
1.1056    raeburn  13679:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13680:         $titles,$wantform) = @_;
1.1055    raeburn  13681:     my $count = 0;
                   13682:     my $depth = 0;
                   13683:     my $datatable;
1.1056    raeburn  13684:     my @hierarchy;
1.1055    raeburn  13685:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13686:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13687:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13688:     foreach my $item (@{$contents}) {
                   13689:         $count ++;
1.1056    raeburn  13690:         @{$dirorder->{$count}} = @hierarchy;
                   13691:         $titles->{$count} = $item;
1.1055    raeburn  13692:         &archive_hierarchy($depth,$count,$parent,$children);
                   13693:         if ($wantform) {
                   13694:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13695:                                        $currdir,$depth,$count);
                   13696:         }
                   13697:         if ($is_dir->{$item}) {
                   13698:             $depth ++;
1.1056    raeburn  13699:             push(@hierarchy,$count);
                   13700:             $parent->{$depth} = $count;
1.1055    raeburn  13701:             $datatable .=
                   13702:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13703:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13704:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13705:             $depth --;
1.1056    raeburn  13706:             pop(@hierarchy);
1.1055    raeburn  13707:         }
                   13708:     }
                   13709:     return ($count,$datatable);
                   13710: }
                   13711: 
                   13712: sub recurse_extracted_archive {
1.1056    raeburn  13713:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13714:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13715:     my $result='';
1.1056    raeburn  13716:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13717:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13718:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13719:         return $result;
                   13720:     }
                   13721:     my $dirptr = 16384;
                   13722:     my ($newdirlistref,$newlisterror) =
                   13723:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13724:     if (ref($newdirlistref) eq 'ARRAY') {
                   13725:         foreach my $dir_line (@{$newdirlistref}) {
                   13726:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13727:             unless ($item =~ /^\.+$/) {
                   13728:                 $$count ++;
1.1056    raeburn  13729:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13730:                 $titles->{$$count} = $item;
1.1055    raeburn  13731:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13732: 
1.1055    raeburn  13733:                 my $is_dir;
                   13734:                 if ($dirptr&$testdir) {
                   13735:                     $is_dir = 1;
                   13736:                 }
                   13737:                 if ($wantform) {
                   13738:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13739:                 }
                   13740:                 if ($is_dir) {
                   13741:                     $$depth ++;
1.1056    raeburn  13742:                     push(@{$hierarchy},$$count);
                   13743:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13744:                     $result .=
                   13745:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13746:                                                    $docuname,$depth,$count,
1.1056    raeburn  13747:                                                    $hierarchy,$dirorder,$children,
                   13748:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13749:                     $$depth --;
1.1056    raeburn  13750:                     pop(@{$hierarchy});
1.1055    raeburn  13751:                 }
                   13752:             }
                   13753:         }
                   13754:     }
                   13755:     return $result;
                   13756: }
                   13757: 
                   13758: sub archive_hierarchy {
                   13759:     my ($depth,$count,$parent,$children) =@_;
                   13760:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13761:         if (exists($parent->{$depth})) {
                   13762:              $children->{$parent->{$depth}} .= $count.':';
                   13763:         }
                   13764:     }
                   13765:     return;
                   13766: }
                   13767: 
                   13768: sub archive_row {
                   13769:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13770:     my ($name) = ($item =~ m{([^/]+)$});
                   13771:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13772:                                        'display'    => 'Add as file',
1.1055    raeburn  13773:                                        'dependency' => 'Include as dependency',
                   13774:                                        'discard'    => 'Discard',
                   13775:                                       );
                   13776:     if ($is_dir) {
1.1059    raeburn  13777:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13778:     }
1.1056    raeburn  13779:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13780:     my $offset = 0;
1.1055    raeburn  13781:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13782:         $offset ++;
1.1065    raeburn  13783:         if ($action ne 'display') {
                   13784:             $offset ++;
                   13785:         }  
1.1055    raeburn  13786:         $output .= '<td><span class="LC_nobreak">'.
                   13787:                    '<label><input type="radio" name="archive_'.$count.
                   13788:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13789:         my $text = $choices{$action};
                   13790:         if ($is_dir) {
                   13791:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13792:             if ($action eq 'display') {
1.1059    raeburn  13793:                 $text = &mt('Add as folder');
1.1055    raeburn  13794:             }
1.1056    raeburn  13795:         } else {
                   13796:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13797: 
                   13798:         }
                   13799:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13800:         if ($action eq 'dependency') {
                   13801:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13802:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13803:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13804:                        '<option value=""></option>'."\n".
                   13805:                        '</select>'."\n".
                   13806:                        '</div>';
1.1059    raeburn  13807:         } elsif ($action eq 'display') {
                   13808:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13809:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13810:                        '</div>';
1.1055    raeburn  13811:         }
1.1056    raeburn  13812:         $output .= '</td>';
1.1055    raeburn  13813:     }
                   13814:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13815:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13816:     for (my $i=0; $i<$depth; $i++) {
                   13817:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13818:     }
                   13819:     if ($is_dir) {
                   13820:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13821:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13822:     } else {
                   13823:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13824:     }
                   13825:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13826:                &end_data_table_row();
                   13827:     return $output;
                   13828: }
                   13829: 
                   13830: sub archive_options_form {
1.1065    raeburn  13831:     my ($form,$display,$count,$hiddenelem) = @_;
                   13832:     my %lt = &Apache::lonlocal::texthash(
                   13833:                perm => 'Permanently remove archive file?',
                   13834:                hows => 'How should each extracted item be incorporated in the course?',
                   13835:                cont => 'Content actions for all',
                   13836:                addf => 'Add as folder/file',
                   13837:                incd => 'Include as dependency for a displayed file',
                   13838:                disc => 'Discard',
                   13839:                no   => 'No',
                   13840:                yes  => 'Yes',
                   13841:                save => 'Save',
                   13842:     );
                   13843:     my $output = <<"END";
                   13844: <form name="$form" method="post" action="">
                   13845: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13846: <label>
                   13847:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13848: </label>
                   13849: &nbsp;
                   13850: <label>
                   13851:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13852: </span>
                   13853: </p>
                   13854: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13855: <br />$lt{'hows'}
                   13856: <div class="LC_columnSection">
                   13857:   <fieldset>
                   13858:     <legend>$lt{'cont'}</legend>
                   13859:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13860:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13861:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13862:   </fieldset>
                   13863: </div>
                   13864: END
                   13865:     return $output.
1.1055    raeburn  13866:            &start_data_table()."\n".
1.1065    raeburn  13867:            $display."\n".
1.1055    raeburn  13868:            &end_data_table()."\n".
                   13869:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13870:            $hiddenelem.
1.1065    raeburn  13871:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13872:            '</form>';
                   13873: }
                   13874: 
                   13875: sub archive_javascript {
1.1056    raeburn  13876:     my ($startcount,$numitems,$titles,$children) = @_;
                   13877:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13878:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13879:     my $scripttag = <<START;
                   13880: <script type="text/javascript">
                   13881: // <![CDATA[
                   13882: 
                   13883: function checkAll(form,prefix) {
                   13884:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13885:     for (var i=0; i < form.elements.length; i++) {
                   13886:         var id = form.elements[i].id;
                   13887:         if ((id != '') && (id != undefined)) {
                   13888:             if (idstr.test(id)) {
                   13889:                 if (form.elements[i].type == 'radio') {
                   13890:                     form.elements[i].checked = true;
1.1056    raeburn  13891:                     var nostart = i-$startcount;
1.1059    raeburn  13892:                     var offset = nostart%7;
                   13893:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13894:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13895:                 }
                   13896:             }
                   13897:         }
                   13898:     }
                   13899: }
                   13900: 
                   13901: function propagateCheck(form,count) {
                   13902:     if (count > 0) {
1.1059    raeburn  13903:         var startelement = $startcount + ((count-1) * 7);
                   13904:         for (var j=1; j<6; j++) {
                   13905:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13906:                 var item = startelement + j; 
                   13907:                 if (form.elements[item].type == 'radio') {
                   13908:                     if (form.elements[item].checked) {
                   13909:                         containerCheck(form,count,j);
                   13910:                         break;
                   13911:                     }
1.1055    raeburn  13912:                 }
                   13913:             }
                   13914:         }
                   13915:     }
                   13916: }
                   13917: 
                   13918: numitems = $numitems
1.1056    raeburn  13919: var titles = new Array(numitems);
                   13920: var parents = new Array(numitems);
1.1055    raeburn  13921: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13922:     parents[i] = new Array;
1.1055    raeburn  13923: }
1.1059    raeburn  13924: var maintitle = '$maintitle';
1.1055    raeburn  13925: 
                   13926: START
                   13927: 
1.1056    raeburn  13928:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13929:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13930:         for (my $i=0; $i<@contents; $i ++) {
                   13931:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13932:         }
                   13933:     }
                   13934: 
1.1056    raeburn  13935:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13936:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13937:     }
                   13938: 
1.1055    raeburn  13939:     $scripttag .= <<END;
                   13940: 
                   13941: function containerCheck(form,count,offset) {
                   13942:     if (count > 0) {
1.1056    raeburn  13943:         dependencyCheck(form,count,offset);
1.1059    raeburn  13944:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13945:         form.elements[item].checked = true;
                   13946:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13947:             if (parents[count].length > 0) {
                   13948:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13949:                     containerCheck(form,parents[count][j],offset);
                   13950:                 }
                   13951:             }
                   13952:         }
                   13953:     }
                   13954: }
                   13955: 
                   13956: function dependencyCheck(form,count,offset) {
                   13957:     if (count > 0) {
1.1059    raeburn  13958:         var chosen = (offset+$startcount)+7*(count-1);
                   13959:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13960:         var currtype = form.elements[depitem].type;
                   13961:         if (form.elements[chosen].value == 'dependency') {
                   13962:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13963:             form.elements[depitem].options.length = 0;
                   13964:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13965:             for (var i=1; i<=numitems; i++) {
                   13966:                 if (i == count) {
                   13967:                     continue;
                   13968:                 }
1.1059    raeburn  13969:                 var startelement = $startcount + (i-1) * 7;
                   13970:                 for (var j=1; j<6; j++) {
                   13971:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13972:                         var item = startelement + j;
                   13973:                         if (form.elements[item].type == 'radio') {
                   13974:                             if (form.elements[item].checked) {
                   13975:                                 if (form.elements[item].value == 'display') {
                   13976:                                     var n = form.elements[depitem].options.length;
                   13977:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13978:                                 }
                   13979:                             }
                   13980:                         }
                   13981:                     }
                   13982:                 }
                   13983:             }
                   13984:         } else {
                   13985:             document.getElementById('arc_depon_'+count).style.display='none';
                   13986:             form.elements[depitem].options.length = 0;
                   13987:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13988:         }
1.1059    raeburn  13989:         titleCheck(form,count,offset);
1.1056    raeburn  13990:     }
                   13991: }
                   13992: 
                   13993: function propagateSelect(form,count,offset) {
                   13994:     if (count > 0) {
1.1065    raeburn  13995:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13996:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13997:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13998:             if (parents[count].length > 0) {
                   13999:                 for (var j=0; j<parents[count].length; j++) {
                   14000:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14001:                 }
                   14002:             }
                   14003:         }
                   14004:     }
                   14005: }
1.1056    raeburn  14006: 
                   14007: function containerSelect(form,count,offset,picked) {
                   14008:     if (count > 0) {
1.1065    raeburn  14009:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14010:         if (form.elements[item].type == 'radio') {
                   14011:             if (form.elements[item].value == 'dependency') {
                   14012:                 if (form.elements[item+1].type == 'select-one') {
                   14013:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14014:                         if (form.elements[item+1].options[i].value == picked) {
                   14015:                             form.elements[item+1].selectedIndex = i;
                   14016:                             break;
                   14017:                         }
                   14018:                     }
                   14019:                 }
                   14020:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14021:                     if (parents[count].length > 0) {
                   14022:                         for (var j=0; j<parents[count].length; j++) {
                   14023:                             containerSelect(form,parents[count][j],offset,picked);
                   14024:                         }
                   14025:                     }
                   14026:                 }
                   14027:             }
                   14028:         }
                   14029:     }
                   14030: }
                   14031: 
1.1059    raeburn  14032: function titleCheck(form,count,offset) {
                   14033:     if (count > 0) {
                   14034:         var chosen = (offset+$startcount)+7*(count-1);
                   14035:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14036:         var currtype = form.elements[depitem].type;
                   14037:         if (form.elements[chosen].value == 'display') {
                   14038:             document.getElementById('arc_title_'+count).style.display='block';
                   14039:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14040:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14041:             }
                   14042:         } else {
                   14043:             document.getElementById('arc_title_'+count).style.display='none';
                   14044:             if (currtype == 'text') { 
                   14045:                 document.getElementById('archive_title_'+count).value='';
                   14046:             }
                   14047:         }
                   14048:     }
                   14049:     return;
                   14050: }
                   14051: 
1.1055    raeburn  14052: // ]]>
                   14053: </script>
                   14054: END
                   14055:     return $scripttag;
                   14056: }
                   14057: 
                   14058: sub process_extracted_files {
1.1067    raeburn  14059:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14060:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14061:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14062:     my @ids=&Apache::lonnet::current_machine_ids();
                   14063:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14064:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14065:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14066:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14067:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14068:         $pathtocheck = "$dir_root/$destination";
                   14069:         $dir = $dir_root;
                   14070:         $ishome = 1;
                   14071:     } else {
                   14072:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14073:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14074:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14075:     }
                   14076:     my $currdir = "$dir_root/$destination";
                   14077:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14078:     if ($env{'form.folderpath'}) {
                   14079:         my @items = split('&',$env{'form.folderpath'});
                   14080:         $folders{'0'} = $items[-2];
1.1099    raeburn  14081:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14082:             $containers{'0'}='page';
                   14083:         } else {  
                   14084:             $containers{'0'}='sequence';
                   14085:         }
1.1055    raeburn  14086:     }
                   14087:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14088:     if ($numitems) {
                   14089:         for (my $i=1; $i<=$numitems; $i++) {
                   14090:             my $path = $env{'form.archive_content_'.$i};
                   14091:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14092:                 my $item = $1;
                   14093:                 $toplevelitems{$item} = $i;
                   14094:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14095:                     $is_dir{$item} = 1;
                   14096:                 }
                   14097:             }
                   14098:         }
                   14099:     }
1.1067    raeburn  14100:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14101:     if (keys(%toplevelitems) > 0) {
                   14102:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14103:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14104:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14105:     }
1.1066    raeburn  14106:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14107:     if ($numitems) {
                   14108:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14109:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14110:             my $path = $env{'form.archive_content_'.$i};
                   14111:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14112:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14113:                     if ($prefix ne '' && $path ne '') {
                   14114:                         if (-e $prefix.$path) {
1.1066    raeburn  14115:                             if ((@archdirs > 0) && 
                   14116:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14117:                                 $todeletedir{$prefix.$path} = 1;
                   14118:                             } else {
                   14119:                                 $todelete{$prefix.$path} = 1;
                   14120:                             }
1.1055    raeburn  14121:                         }
                   14122:                     }
                   14123:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14124:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14125:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14126:                     $docstitle = $env{'form.archive_title_'.$i};
                   14127:                     if ($docstitle eq '') {
                   14128:                         $docstitle = $title;
                   14129:                     }
1.1055    raeburn  14130:                     $outer = 0;
1.1056    raeburn  14131:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14132:                         if (@{$dirorder{$i}} > 0) {
                   14133:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14134:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14135:                                     $outer = $item;
                   14136:                                     last;
                   14137:                                 }
                   14138:                             }
                   14139:                         }
                   14140:                     }
                   14141:                     my ($errtext,$fatal) = 
                   14142:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14143:                                                '/'.$folders{$outer}.'.'.
                   14144:                                                $containers{$outer});
                   14145:                     next if ($fatal);
                   14146:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14147:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14148:                             $mapinner{$i} = time;
1.1055    raeburn  14149:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14150:                             $containers{$i} = 'sequence';
                   14151:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14152:                                       $folders{$i}.'.'.$containers{$i};
                   14153:                             my $newidx = &LONCAPA::map::getresidx();
                   14154:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14155:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14156:                             push(@LONCAPA::map::order,$newidx);
                   14157:                             my ($outtext,$errtext) =
                   14158:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14159:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14160:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14161:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14162:                             unless ($errtext) {
1.1294    raeburn  14163:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14164:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14165:                                             '</li>'."\n";
1.1067    raeburn  14166:                             }
1.1055    raeburn  14167:                         }
                   14168:                     } else {
                   14169:                         if ($context eq 'coursedocs') {
                   14170:                             my $newidx=&LONCAPA::map::getresidx();
                   14171:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14172:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14173:                                       $title;
1.1294    raeburn  14174:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   14175:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14176:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14177:                                 }
                   14178:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14179:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14180:                                 }
                   14181:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14182:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14183:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14184:                                         unless ($ishome) {
                   14185:                                             my $fetch = "$newdest{$i}/$title";
                   14186:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14187:                                             $prompttofetch{$fetch} = 1;
                   14188:                                         }
1.1292    raeburn  14189:                                     }
1.1067    raeburn  14190:                                 }
1.1294    raeburn  14191:                                 $LONCAPA::map::resources[$newidx]=
                   14192:                                     $docstitle.':'.$url.':false:normal:res';
                   14193:                                 push(@LONCAPA::map::order, $newidx);
                   14194:                                 my ($outtext,$errtext)=
                   14195:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14196:                                                             $docuname.'/'.$folders{$outer}.
                   14197:                                                             '.'.$containers{$outer},1,1);
                   14198:                                 unless ($errtext) {
                   14199:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14200:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14201:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14202:                                                    '</li>'."\n";
                   14203:                                     }
1.1067    raeburn  14204:                                 }
1.1294    raeburn  14205:                             } else {
                   14206:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14207:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14208:                             }
1.1055    raeburn  14209:                         }
                   14210:                     }
1.1086    raeburn  14211:                 }
                   14212:             } else {
1.1294    raeburn  14213:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14214:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14215:             }
                   14216:         }
                   14217:         for (my $i=1; $i<=$numitems; $i++) {
                   14218:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14219:             my $path = $env{'form.archive_content_'.$i};
                   14220:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14221:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14222:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14223:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14224:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14225:                         my ($itemidx,$fullpath,$relpath);
                   14226:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14227:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14228:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14229:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14230:                                     $itemidx = $j;
1.1056    raeburn  14231:                                 }
                   14232:                             }
1.1086    raeburn  14233:                         }
                   14234:                         if ($itemidx eq '') {
                   14235:                             $itemidx =  0;
                   14236:                         } 
                   14237:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14238:                             if ($mapinner{$referrer{$i}}) {
                   14239:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14240:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14241:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14242:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14243:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14244:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14245:                                             if (!-e $fullpath) {
                   14246:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14247:                                             }
                   14248:                                         }
1.1086    raeburn  14249:                                     } else {
                   14250:                                         last;
1.1056    raeburn  14251:                                     }
1.1086    raeburn  14252:                                 }
                   14253:                             }
                   14254:                         } elsif ($newdest{$referrer{$i}}) {
                   14255:                             $fullpath = $newdest{$referrer{$i}};
                   14256:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14257:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14258:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14259:                                     last;
                   14260:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14261:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14262:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14263:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14264:                                         if (!-e $fullpath) {
                   14265:                                             mkdir($fullpath,0755);
1.1056    raeburn  14266:                                         }
                   14267:                                     }
1.1086    raeburn  14268:                                 } else {
                   14269:                                     last;
1.1056    raeburn  14270:                                 }
1.1055    raeburn  14271:                             }
                   14272:                         }
1.1086    raeburn  14273:                         if ($fullpath ne '') {
                   14274:                             if (-e "$prefix$path") {
1.1292    raeburn  14275:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14276:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14277:                                 }
1.1086    raeburn  14278:                             }
                   14279:                             if (-e "$fullpath/$title") {
                   14280:                                 my $showpath;
                   14281:                                 if ($relpath ne '') {
                   14282:                                     $showpath = "$relpath/$title";
                   14283:                                 } else {
                   14284:                                     $showpath = "/$title";
                   14285:                                 } 
1.1294    raeburn  14286:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14287:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14288:                                            '</li>'."\n";
1.1292    raeburn  14289:                                 unless ($ishome) {
                   14290:                                     my $fetch = "$fullpath/$title";
                   14291:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14292:                                     $prompttofetch{$fetch} = 1;
                   14293:                                 }
1.1086    raeburn  14294:                             }
                   14295:                         }
1.1055    raeburn  14296:                     }
1.1086    raeburn  14297:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14298:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14299:                                     &HTML::Entities::encode($path,'<>&"'),
                   14300:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14301:                                 '<br />';
1.1055    raeburn  14302:                 }
                   14303:             } else {
1.1294    raeburn  14304:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14305:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14306:             }
                   14307:         }
                   14308:         if (keys(%todelete)) {
                   14309:             foreach my $key (keys(%todelete)) {
                   14310:                 unlink($key);
1.1066    raeburn  14311:             }
                   14312:         }
                   14313:         if (keys(%todeletedir)) {
                   14314:             foreach my $key (keys(%todeletedir)) {
                   14315:                 rmdir($key);
                   14316:             }
                   14317:         }
                   14318:         foreach my $dir (sort(keys(%is_dir))) {
                   14319:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14320:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14321:             }
                   14322:         }
1.1067    raeburn  14323:         if ($result ne '') {
                   14324:             $output .= '<ul>'."\n".
                   14325:                        $result."\n".
                   14326:                        '</ul>';
                   14327:         }
                   14328:         unless ($ishome) {
                   14329:             my $replicationfail;
                   14330:             foreach my $item (keys(%prompttofetch)) {
                   14331:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14332:                 unless ($fetchresult eq 'ok') {
                   14333:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14334:                 }
                   14335:             }
                   14336:             if ($replicationfail) {
                   14337:                 $output .= '<p class="LC_error">'.
                   14338:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14339:                            $replicationfail.
                   14340:                            '</ul></p>';
                   14341:             }
                   14342:         }
1.1055    raeburn  14343:     } else {
                   14344:         $warning = &mt('No items found in archive.');
                   14345:     }
                   14346:     if ($error) {
                   14347:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14348:                    $error.'</p>'."\n";
                   14349:     }
                   14350:     if ($warning) {
                   14351:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14352:     }
                   14353:     return $output;
                   14354: }
                   14355: 
1.1066    raeburn  14356: sub cleanup_empty_dirs {
                   14357:     my ($path) = @_;
                   14358:     if (($path ne '') && (-d $path)) {
                   14359:         if (opendir(my $dirh,$path)) {
                   14360:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14361:             my $numitems = 0;
                   14362:             foreach my $item (@dircontents) {
                   14363:                 if (-d "$path/$item") {
1.1111    raeburn  14364:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14365:                     if (-e "$path/$item") {
                   14366:                         $numitems ++;
                   14367:                     }
                   14368:                 } else {
                   14369:                     $numitems ++;
                   14370:                 }
                   14371:             }
                   14372:             if ($numitems == 0) {
                   14373:                 rmdir($path);
                   14374:             }
                   14375:             closedir($dirh);
                   14376:         }
                   14377:     }
                   14378:     return;
                   14379: }
                   14380: 
1.41      ng       14381: =pod
1.45      matthew  14382: 
1.1162    raeburn  14383: =item * &get_folder_hierarchy()
1.1068    raeburn  14384: 
                   14385: Provides hierarchy of names of folders/sub-folders containing the current
                   14386: item,
                   14387: 
                   14388: Inputs: 3
                   14389:      - $navmap - navmaps object
                   14390: 
                   14391:      - $map - url for map (either the trigger itself, or map containing
                   14392:                            the resource, which is the trigger).
                   14393: 
                   14394:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14395: 
                   14396: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14397: 
                   14398: =cut
                   14399: 
                   14400: sub get_folder_hierarchy {
                   14401:     my ($navmap,$map,$showitem) = @_;
                   14402:     my @pathitems;
                   14403:     if (ref($navmap)) {
                   14404:         my $mapres = $navmap->getResourceByUrl($map);
                   14405:         if (ref($mapres)) {
                   14406:             my $pcslist = $mapres->map_hierarchy();
                   14407:             if ($pcslist ne '') {
                   14408:                 my @pcs = split(/,/,$pcslist);
                   14409:                 foreach my $pc (@pcs) {
                   14410:                     if ($pc == 1) {
1.1129    raeburn  14411:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14412:                     } else {
                   14413:                         my $res = $navmap->getByMapPc($pc);
                   14414:                         if (ref($res)) {
                   14415:                             my $title = $res->compTitle();
                   14416:                             $title =~ s/\W+/_/g;
                   14417:                             if ($title ne '') {
                   14418:                                 push(@pathitems,$title);
                   14419:                             }
                   14420:                         }
                   14421:                     }
                   14422:                 }
                   14423:             }
1.1071    raeburn  14424:             if ($showitem) {
                   14425:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14426:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14427:                 } else {
                   14428:                     my $maptitle = $mapres->compTitle();
                   14429:                     $maptitle =~ s/\W+/_/g;
                   14430:                     if ($maptitle ne '') {
                   14431:                         push(@pathitems,$maptitle);
                   14432:                     }
1.1068    raeburn  14433:                 }
                   14434:             }
                   14435:         }
                   14436:     }
                   14437:     return @pathitems;
                   14438: }
                   14439: 
                   14440: =pod
                   14441: 
1.1015    raeburn  14442: =item * &get_turnedin_filepath()
                   14443: 
                   14444: Determines path in a user's portfolio file for storage of files uploaded
                   14445: to a specific essayresponse or dropbox item.
                   14446: 
                   14447: Inputs: 3 required + 1 optional.
                   14448: $symb is symb for resource, $uname and $udom are for current user (required).
                   14449: $caller is optional (can be "submission", if routine is called when storing
                   14450: an upoaded file when "Submit Answer" button was pressed).
                   14451: 
                   14452: Returns array containing $path and $multiresp. 
                   14453: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14454: than one file upload item.  Callers of routine should append partid as a 
                   14455: subdirectory to $path in cases where $multiresp is 1.
                   14456: 
                   14457: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14458: 
                   14459: =cut
                   14460: 
                   14461: sub get_turnedin_filepath {
                   14462:     my ($symb,$uname,$udom,$caller) = @_;
                   14463:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14464:     my $turnindir;
                   14465:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14466:     $turnindir = $userhash{'turnindir'};
                   14467:     my ($path,$multiresp);
                   14468:     if ($turnindir eq '') {
                   14469:         if ($caller eq 'submission') {
                   14470:             $turnindir = &mt('turned in');
                   14471:             $turnindir =~ s/\W+/_/g;
                   14472:             my %newhash = (
                   14473:                             'turnindir' => $turnindir,
                   14474:                           );
                   14475:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14476:         }
                   14477:     }
                   14478:     if ($turnindir ne '') {
                   14479:         $path = '/'.$turnindir.'/';
                   14480:         my ($multipart,$turnin,@pathitems);
                   14481:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14482:         if (defined($navmap)) {
                   14483:             my $mapres = $navmap->getResourceByUrl($map);
                   14484:             if (ref($mapres)) {
                   14485:                 my $pcslist = $mapres->map_hierarchy();
                   14486:                 if ($pcslist ne '') {
                   14487:                     foreach my $pc (split(/,/,$pcslist)) {
                   14488:                         my $res = $navmap->getByMapPc($pc);
                   14489:                         if (ref($res)) {
                   14490:                             my $title = $res->compTitle();
                   14491:                             $title =~ s/\W+/_/g;
                   14492:                             if ($title ne '') {
1.1149    raeburn  14493:                                 if (($pc > 1) && (length($title) > 12)) {
                   14494:                                     $title = substr($title,0,12);
                   14495:                                 }
1.1015    raeburn  14496:                                 push(@pathitems,$title);
                   14497:                             }
                   14498:                         }
                   14499:                     }
                   14500:                 }
                   14501:                 my $maptitle = $mapres->compTitle();
                   14502:                 $maptitle =~ s/\W+/_/g;
                   14503:                 if ($maptitle ne '') {
1.1149    raeburn  14504:                     if (length($maptitle) > 12) {
                   14505:                         $maptitle = substr($maptitle,0,12);
                   14506:                     }
1.1015    raeburn  14507:                     push(@pathitems,$maptitle);
                   14508:                 }
                   14509:                 unless ($env{'request.state'} eq 'construct') {
                   14510:                     my $res = $navmap->getBySymb($symb);
                   14511:                     if (ref($res)) {
                   14512:                         my $partlist = $res->parts();
                   14513:                         my $totaluploads = 0;
                   14514:                         if (ref($partlist) eq 'ARRAY') {
                   14515:                             foreach my $part (@{$partlist}) {
                   14516:                                 my @types = $res->responseType($part);
                   14517:                                 my @ids = $res->responseIds($part);
                   14518:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14519:                                     if ($types[$i] eq 'essay') {
                   14520:                                         my $partid = $part.'_'.$ids[$i];
                   14521:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14522:                                             $totaluploads ++;
                   14523:                                         }
                   14524:                                     }
                   14525:                                 }
                   14526:                             }
                   14527:                             if ($totaluploads > 1) {
                   14528:                                 $multiresp = 1;
                   14529:                             }
                   14530:                         }
                   14531:                     }
                   14532:                 }
                   14533:             } else {
                   14534:                 return;
                   14535:             }
                   14536:         } else {
                   14537:             return;
                   14538:         }
                   14539:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14540:         $restitle =~ s/\W+/_/g;
                   14541:         if ($restitle eq '') {
                   14542:             $restitle = ($resurl =~ m{/[^/]+$});
                   14543:             if ($restitle eq '') {
                   14544:                 $restitle = time;
                   14545:             }
                   14546:         }
1.1149    raeburn  14547:         if (length($restitle) > 12) {
                   14548:             $restitle = substr($restitle,0,12);
                   14549:         }
1.1015    raeburn  14550:         push(@pathitems,$restitle);
                   14551:         $path .= join('/',@pathitems);
                   14552:     }
                   14553:     return ($path,$multiresp);
                   14554: }
                   14555: 
                   14556: =pod
                   14557: 
1.464     albertel 14558: =back
1.41      ng       14559: 
1.112     bowersj2 14560: =head1 CSV Upload/Handling functions
1.38      albertel 14561: 
1.41      ng       14562: =over 4
                   14563: 
1.648     raeburn  14564: =item * &upfile_store($r)
1.41      ng       14565: 
                   14566: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14567: needs $env{'form.upfile'}
1.41      ng       14568: returns $datatoken to be put into hidden field
                   14569: 
                   14570: =cut
1.31      albertel 14571: 
                   14572: sub upfile_store {
                   14573:     my $r=shift;
1.258     albertel 14574:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14575:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14576:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14577:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14578: 
1.1299    raeburn  14579:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14580:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14581:                                      time.'_'.$$);
                   14582:     return if ($datatoken eq '');
                   14583: 
1.31      albertel 14584:     {
1.158     raeburn  14585:         my $datafile = $r->dir_config('lonDaemons').
                   14586:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14587:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14588:             print $fh $env{'form.upfile'};
1.158     raeburn  14589:             close($fh);
                   14590:         }
1.31      albertel 14591:     }
                   14592:     return $datatoken;
                   14593: }
                   14594: 
1.56      matthew  14595: =pod
                   14596: 
1.1290    raeburn  14597: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14598: 
                   14599: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14600: $datatoken is the name to assign to the temporary file.
1.258     albertel 14601: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14602: 
                   14603: =cut
1.31      albertel 14604: 
                   14605: sub load_tmp_file {
1.1290    raeburn  14606:     my ($r,$datatoken) = @_;
                   14607:     return if ($datatoken eq '');
1.31      albertel 14608:     my @studentdata=();
                   14609:     {
1.158     raeburn  14610:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14611:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14612:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14613:             @studentdata=<$fh>;
                   14614:             close($fh);
                   14615:         }
1.31      albertel 14616:     }
1.258     albertel 14617:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14618: }
                   14619: 
1.1290    raeburn  14620: sub valid_datatoken {
                   14621:     my ($datatoken) = @_;
1.1325    raeburn  14622:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14623:         return $datatoken;
                   14624:     }
                   14625:     return;
                   14626: }
                   14627: 
1.56      matthew  14628: =pod
                   14629: 
1.648     raeburn  14630: =item * &upfile_record_sep()
1.41      ng       14631: 
                   14632: Separate uploaded file into records
                   14633: returns array of records,
1.258     albertel 14634: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14635: 
                   14636: =cut
1.31      albertel 14637: 
                   14638: sub upfile_record_sep {
1.258     albertel 14639:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14640:     } else {
1.248     albertel 14641: 	my @records;
1.258     albertel 14642: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14643: 	    if ($line=~/^\s*$/) { next; }
                   14644: 	    push(@records,$line);
                   14645: 	}
                   14646: 	return @records;
1.31      albertel 14647:     }
                   14648: }
                   14649: 
1.56      matthew  14650: =pod
                   14651: 
1.648     raeburn  14652: =item * &record_sep($record)
1.41      ng       14653: 
1.258     albertel 14654: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14655: 
                   14656: =cut
                   14657: 
1.263     www      14658: sub takeleft {
                   14659:     my $index=shift;
                   14660:     return substr('0000'.$index,-4,4);
                   14661: }
                   14662: 
1.31      albertel 14663: sub record_sep {
                   14664:     my $record=shift;
                   14665:     my %components=();
1.258     albertel 14666:     if ($env{'form.upfiletype'} eq 'xml') {
                   14667:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14668:         my $i=0;
1.356     albertel 14669:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14670:             $field=~s/^(\"|\')//;
                   14671:             $field=~s/(\"|\')$//;
1.263     www      14672:             $components{&takeleft($i)}=$field;
1.31      albertel 14673:             $i++;
                   14674:         }
1.258     albertel 14675:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14676:         my $i=0;
1.356     albertel 14677:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14678:             $field=~s/^(\"|\')//;
                   14679:             $field=~s/(\"|\')$//;
1.263     www      14680:             $components{&takeleft($i)}=$field;
1.31      albertel 14681:             $i++;
                   14682:         }
                   14683:     } else {
1.561     www      14684:         my $separator=',';
1.480     banghart 14685:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14686:             $separator=';';
1.480     banghart 14687:         }
1.31      albertel 14688:         my $i=0;
1.561     www      14689: # the character we are looking for to indicate the end of a quote or a record 
                   14690:         my $looking_for=$separator;
                   14691: # do not add the characters to the fields
                   14692:         my $ignore=0;
                   14693: # we just encountered a separator (or the beginning of the record)
                   14694:         my $just_found_separator=1;
                   14695: # store the field we are working on here
                   14696:         my $field='';
                   14697: # work our way through all characters in record
                   14698:         foreach my $character ($record=~/(.)/g) {
                   14699:             if ($character eq $looking_for) {
                   14700:                if ($character ne $separator) {
                   14701: # Found the end of a quote, again looking for separator
                   14702:                   $looking_for=$separator;
                   14703:                   $ignore=1;
                   14704:                } else {
                   14705: # Found a separator, store away what we got
                   14706:                   $components{&takeleft($i)}=$field;
                   14707: 	          $i++;
                   14708:                   $just_found_separator=1;
                   14709:                   $ignore=0;
                   14710:                   $field='';
                   14711:                }
                   14712:                next;
                   14713:             }
                   14714: # single or double quotation marks after a separator indicate beginning of a quote
                   14715: # we are now looking for the end of the quote and need to ignore separators
                   14716:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14717:                $looking_for=$character;
                   14718:                next;
                   14719:             }
                   14720: # ignore would be true after we reached the end of a quote
                   14721:             if ($ignore) { next; }
                   14722:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14723:             $field.=$character;
                   14724:             $just_found_separator=0; 
1.31      albertel 14725:         }
1.561     www      14726: # catch the very last entry, since we never encountered the separator
                   14727:         $components{&takeleft($i)}=$field;
1.31      albertel 14728:     }
                   14729:     return %components;
                   14730: }
                   14731: 
1.144     matthew  14732: ######################################################
                   14733: ######################################################
                   14734: 
1.56      matthew  14735: =pod
                   14736: 
1.648     raeburn  14737: =item * &upfile_select_html()
1.41      ng       14738: 
1.144     matthew  14739: Return HTML code to select a file from the users machine and specify 
                   14740: the file type.
1.41      ng       14741: 
                   14742: =cut
                   14743: 
1.144     matthew  14744: ######################################################
                   14745: ######################################################
1.31      albertel 14746: sub upfile_select_html {
1.144     matthew  14747:     my %Types = (
                   14748:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14749:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14750:                  space => &mt('Space separated'),
                   14751:                  tab   => &mt('Tabulator separated'),
                   14752: #                 xml   => &mt('HTML/XML'),
                   14753:                  );
                   14754:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14755:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14756:     foreach my $type (sort(keys(%Types))) {
                   14757:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14758:     }
                   14759:     $Str .= "</select>\n";
                   14760:     return $Str;
1.31      albertel 14761: }
                   14762: 
1.301     albertel 14763: sub get_samples {
                   14764:     my ($records,$toget) = @_;
                   14765:     my @samples=({});
                   14766:     my $got=0;
                   14767:     foreach my $rec (@$records) {
                   14768: 	my %temp = &record_sep($rec);
                   14769: 	if (! grep(/\S/, values(%temp))) { next; }
                   14770: 	if (%temp) {
                   14771: 	    $samples[$got]=\%temp;
                   14772: 	    $got++;
                   14773: 	    if ($got == $toget) { last; }
                   14774: 	}
                   14775:     }
                   14776:     return \@samples;
                   14777: }
                   14778: 
1.144     matthew  14779: ######################################################
                   14780: ######################################################
                   14781: 
1.56      matthew  14782: =pod
                   14783: 
1.648     raeburn  14784: =item * &csv_print_samples($r,$records)
1.41      ng       14785: 
                   14786: Prints a table of sample values from each column uploaded $r is an
                   14787: Apache Request ref, $records is an arrayref from
                   14788: &Apache::loncommon::upfile_record_sep
                   14789: 
                   14790: =cut
                   14791: 
1.144     matthew  14792: ######################################################
                   14793: ######################################################
1.31      albertel 14794: sub csv_print_samples {
                   14795:     my ($r,$records) = @_;
1.662     bisitz   14796:     my $samples = &get_samples($records,5);
1.301     albertel 14797: 
1.594     raeburn  14798:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14799:               &start_data_table_header_row());
1.356     albertel 14800:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14801:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14802:     $r->print(&end_data_table_header_row());
1.301     albertel 14803:     foreach my $hash (@$samples) {
1.594     raeburn  14804: 	$r->print(&start_data_table_row());
1.356     albertel 14805: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14806: 	    $r->print('<td>');
1.356     albertel 14807: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14808: 	    $r->print('</td>');
                   14809: 	}
1.594     raeburn  14810: 	$r->print(&end_data_table_row());
1.31      albertel 14811:     }
1.594     raeburn  14812:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14813: }
                   14814: 
1.144     matthew  14815: ######################################################
                   14816: ######################################################
                   14817: 
1.56      matthew  14818: =pod
                   14819: 
1.648     raeburn  14820: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14821: 
                   14822: Prints a table to create associations between values and table columns.
1.144     matthew  14823: 
1.41      ng       14824: $r is an Apache Request ref,
                   14825: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14826: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14827: 
                   14828: =cut
                   14829: 
1.144     matthew  14830: ######################################################
                   14831: ######################################################
1.31      albertel 14832: sub csv_print_select_table {
                   14833:     my ($r,$records,$d) = @_;
1.301     albertel 14834:     my $i=0;
                   14835:     my $samples = &get_samples($records,1);
1.144     matthew  14836:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14837: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14838:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14839:               '<th>'.&mt('Column').'</th>'.
                   14840:               &end_data_table_header_row()."\n");
1.356     albertel 14841:     foreach my $array_ref (@$d) {
                   14842: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14843: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14844: 
1.875     bisitz   14845: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14846: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14847: 	$r->print('<option value="none"></option>');
1.356     albertel 14848: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14849: 	    $r->print('<option value="'.$sample.'"'.
                   14850:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14851:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14852: 	}
1.594     raeburn  14853: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14854: 	$i++;
                   14855:     }
1.594     raeburn  14856:     $r->print(&end_data_table());
1.31      albertel 14857:     $i--;
                   14858:     return $i;
                   14859: }
1.56      matthew  14860: 
1.144     matthew  14861: ######################################################
                   14862: ######################################################
                   14863: 
1.56      matthew  14864: =pod
1.31      albertel 14865: 
1.648     raeburn  14866: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14867: 
                   14868: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14869: 
                   14870: $r is an Apache Request ref,
                   14871: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14872: $d is an array of 2 element arrays (internal name, displayed name)
                   14873: 
                   14874: =cut
                   14875: 
1.144     matthew  14876: ######################################################
                   14877: ######################################################
1.31      albertel 14878: sub csv_samples_select_table {
                   14879:     my ($r,$records,$d) = @_;
                   14880:     my $i=0;
1.144     matthew  14881:     #
1.662     bisitz   14882:     my $max_samples = 5;
                   14883:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14884:     $r->print(&start_data_table().
                   14885:               &start_data_table_header_row().'<th>'.
                   14886:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14887:               &end_data_table_header_row());
1.301     albertel 14888: 
                   14889:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14890: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14891: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14892: 	foreach my $option (@$d) {
                   14893: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14894: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14895:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14896:                       $display.'</option>');
1.31      albertel 14897: 	}
                   14898: 	$r->print('</select></td><td>');
1.662     bisitz   14899: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14900: 	    if (defined($samples->[$line]{$key})) { 
                   14901: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14902: 	    }
                   14903: 	}
1.594     raeburn  14904: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14905: 	$i++;
                   14906:     }
1.594     raeburn  14907:     $r->print(&end_data_table());
1.31      albertel 14908:     $i--;
                   14909:     return($i);
1.115     matthew  14910: }
                   14911: 
1.144     matthew  14912: ######################################################
                   14913: ######################################################
                   14914: 
1.115     matthew  14915: =pod
                   14916: 
1.648     raeburn  14917: =item * &clean_excel_name($name)
1.115     matthew  14918: 
                   14919: Returns a replacement for $name which does not contain any illegal characters.
                   14920: 
                   14921: =cut
                   14922: 
1.144     matthew  14923: ######################################################
                   14924: ######################################################
1.115     matthew  14925: sub clean_excel_name {
                   14926:     my ($name) = @_;
                   14927:     $name =~ s/[:\*\?\/\\]//g;
                   14928:     if (length($name) > 31) {
                   14929:         $name = substr($name,0,31);
                   14930:     }
                   14931:     return $name;
1.25      albertel 14932: }
1.84      albertel 14933: 
1.85      albertel 14934: =pod
                   14935: 
1.648     raeburn  14936: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14937: 
                   14938: Returns either 1 or undef
                   14939: 
                   14940: 1 if the part is to be hidden, undef if it is to be shown
                   14941: 
                   14942: Arguments are:
                   14943: 
                   14944: $id the id of the part to be checked
                   14945: $symb, optional the symb of the resource to check
                   14946: $udom, optional the domain of the user to check for
                   14947: $uname, optional the username of the user to check for
                   14948: 
                   14949: =cut
1.84      albertel 14950: 
                   14951: sub check_if_partid_hidden {
                   14952:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14953:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14954: 					 $symb,$udom,$uname);
1.141     albertel 14955:     my $truth=1;
                   14956:     #if the string starts with !, then the list is the list to show not hide
                   14957:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14958:     my @hiddenlist=split(/,/,$hiddenparts);
                   14959:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14960: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14961:     }
1.141     albertel 14962:     return !$truth;
1.84      albertel 14963: }
1.127     matthew  14964: 
1.138     matthew  14965: 
                   14966: ############################################################
                   14967: ############################################################
                   14968: 
                   14969: =pod
                   14970: 
1.157     matthew  14971: =back 
                   14972: 
1.138     matthew  14973: =head1 cgi-bin script and graphing routines
                   14974: 
1.157     matthew  14975: =over 4
                   14976: 
1.648     raeburn  14977: =item * &get_cgi_id()
1.138     matthew  14978: 
                   14979: Inputs: none
                   14980: 
                   14981: Returns an id which can be used to pass environment variables
                   14982: to various cgi-bin scripts.  These environment variables will
                   14983: be removed from the users environment after a given time by
                   14984: the routine &Apache::lonnet::transfer_profile_to_env.
                   14985: 
                   14986: =cut
                   14987: 
                   14988: ############################################################
                   14989: ############################################################
1.152     albertel 14990: my $uniq=0;
1.136     matthew  14991: sub get_cgi_id {
1.154     albertel 14992:     $uniq=($uniq+1)%100000;
1.280     albertel 14993:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14994: }
                   14995: 
1.127     matthew  14996: ############################################################
                   14997: ############################################################
                   14998: 
                   14999: =pod
                   15000: 
1.648     raeburn  15001: =item * &DrawBarGraph()
1.127     matthew  15002: 
1.138     matthew  15003: Facilitates the plotting of data in a (stacked) bar graph.
                   15004: Puts plot definition data into the users environment in order for 
                   15005: graph.png to plot it.  Returns an <img> tag for the plot.
                   15006: The bars on the plot are labeled '1','2',...,'n'.
                   15007: 
                   15008: Inputs:
                   15009: 
                   15010: =over 4
                   15011: 
                   15012: =item $Title: string, the title of the plot
                   15013: 
                   15014: =item $xlabel: string, text describing the X-axis of the plot
                   15015: 
                   15016: =item $ylabel: string, text describing the Y-axis of the plot
                   15017: 
                   15018: =item $Max: scalar, the maximum Y value to use in the plot
                   15019: If $Max is < any data point, the graph will not be rendered.
                   15020: 
1.140     matthew  15021: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15022: they are plotted.  If undefined, default values will be used.
                   15023: 
1.178     matthew  15024: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15025: 
1.138     matthew  15026: =item @Values: An array of array references.  Each array reference holds data
                   15027: to be plotted in a stacked bar chart.
                   15028: 
1.239     matthew  15029: =item If the final element of @Values is a hash reference the key/value
                   15030: pairs will be added to the graph definition.
                   15031: 
1.138     matthew  15032: =back
                   15033: 
                   15034: Returns:
                   15035: 
                   15036: An <img> tag which references graph.png and the appropriate identifying
                   15037: information for the plot.
                   15038: 
1.127     matthew  15039: =cut
                   15040: 
                   15041: ############################################################
                   15042: ############################################################
1.134     matthew  15043: sub DrawBarGraph {
1.178     matthew  15044:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15045:     #
                   15046:     if (! defined($colors)) {
                   15047:         $colors = ['#33ff00', 
                   15048:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15049:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15050:                   ]; 
                   15051:     }
1.228     matthew  15052:     my $extra_settings = {};
                   15053:     if (ref($Values[-1]) eq 'HASH') {
                   15054:         $extra_settings = pop(@Values);
                   15055:     }
1.127     matthew  15056:     #
1.136     matthew  15057:     my $identifier = &get_cgi_id();
                   15058:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15059:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15060:         return '';
                   15061:     }
1.225     matthew  15062:     #
                   15063:     my @Labels;
                   15064:     if (defined($labels)) {
                   15065:         @Labels = @$labels;
                   15066:     } else {
                   15067:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15068:             push(@Labels,$i+1);
1.225     matthew  15069:         }
                   15070:     }
                   15071:     #
1.129     matthew  15072:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15073:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15074:     my %ValuesHash;
                   15075:     my $NumSets=1;
                   15076:     foreach my $array (@Values) {
                   15077:         next if (! ref($array));
1.136     matthew  15078:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15079:             join(',',@$array);
1.129     matthew  15080:     }
1.127     matthew  15081:     #
1.136     matthew  15082:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15083:     if ($NumBars < 3) {
                   15084:         $width = 120+$NumBars*32;
1.220     matthew  15085:         $xskip = 1;
1.225     matthew  15086:         $bar_width = 30;
                   15087:     } elsif ($NumBars < 5) {
                   15088:         $width = 120+$NumBars*20;
                   15089:         $xskip = 1;
                   15090:         $bar_width = 20;
1.220     matthew  15091:     } elsif ($NumBars < 10) {
1.136     matthew  15092:         $width = 120+$NumBars*15;
                   15093:         $xskip = 1;
                   15094:         $bar_width = 15;
                   15095:     } elsif ($NumBars <= 25) {
                   15096:         $width = 120+$NumBars*11;
                   15097:         $xskip = 5;
                   15098:         $bar_width = 8;
                   15099:     } elsif ($NumBars <= 50) {
                   15100:         $width = 120+$NumBars*8;
                   15101:         $xskip = 5;
                   15102:         $bar_width = 4;
                   15103:     } else {
                   15104:         $width = 120+$NumBars*8;
                   15105:         $xskip = 5;
                   15106:         $bar_width = 4;
                   15107:     }
                   15108:     #
1.137     matthew  15109:     $Max = 1 if ($Max < 1);
                   15110:     if ( int($Max) < $Max ) {
                   15111:         $Max++;
                   15112:         $Max = int($Max);
                   15113:     }
1.127     matthew  15114:     $Title  = '' if (! defined($Title));
                   15115:     $xlabel = '' if (! defined($xlabel));
                   15116:     $ylabel = '' if (! defined($ylabel));
1.369     www      15117:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15118:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15119:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15120:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15121:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15122:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15123:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15124:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15125:     $ValuesHash{$id.'.height'}   = $height;
                   15126:     $ValuesHash{$id.'.width'}    = $width;
                   15127:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15128:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15129:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15130:     #
1.228     matthew  15131:     # Deal with other parameters
                   15132:     while (my ($key,$value) = each(%$extra_settings)) {
                   15133:         $ValuesHash{$id.'.'.$key} = $value;
                   15134:     }
                   15135:     #
1.646     raeburn  15136:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15137:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15138: }
                   15139: 
                   15140: ############################################################
                   15141: ############################################################
                   15142: 
                   15143: =pod
                   15144: 
1.648     raeburn  15145: =item * &DrawXYGraph()
1.137     matthew  15146: 
1.138     matthew  15147: Facilitates the plotting of data in an XY graph.
                   15148: Puts plot definition data into the users environment in order for 
                   15149: graph.png to plot it.  Returns an <img> tag for the plot.
                   15150: 
                   15151: Inputs:
                   15152: 
                   15153: =over 4
                   15154: 
                   15155: =item $Title: string, the title of the plot
                   15156: 
                   15157: =item $xlabel: string, text describing the X-axis of the plot
                   15158: 
                   15159: =item $ylabel: string, text describing the Y-axis of the plot
                   15160: 
                   15161: =item $Max: scalar, the maximum Y value to use in the plot
                   15162: If $Max is < any data point, the graph will not be rendered.
                   15163: 
                   15164: =item $colors: Array ref containing the hex color codes for the data to be 
                   15165: plotted in.  If undefined, default values will be used.
                   15166: 
                   15167: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15168: 
                   15169: =item $Ydata: Array ref containing Array refs.  
1.185     www      15170: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15171: 
                   15172: =item %Values: hash indicating or overriding any default values which are 
                   15173: passed to graph.png.  
                   15174: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15175: 
                   15176: =back
                   15177: 
                   15178: Returns:
                   15179: 
                   15180: An <img> tag which references graph.png and the appropriate identifying
                   15181: information for the plot.
                   15182: 
1.137     matthew  15183: =cut
                   15184: 
                   15185: ############################################################
                   15186: ############################################################
                   15187: sub DrawXYGraph {
                   15188:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15189:     #
                   15190:     # Create the identifier for the graph
                   15191:     my $identifier = &get_cgi_id();
                   15192:     my $id = 'cgi.'.$identifier;
                   15193:     #
                   15194:     $Title  = '' if (! defined($Title));
                   15195:     $xlabel = '' if (! defined($xlabel));
                   15196:     $ylabel = '' if (! defined($ylabel));
                   15197:     my %ValuesHash = 
                   15198:         (
1.369     www      15199:          $id.'.title'  => &escape($Title),
                   15200:          $id.'.xlabel' => &escape($xlabel),
                   15201:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15202:          $id.'.y_max_value'=> $Max,
                   15203:          $id.'.labels'     => join(',',@$Xlabels),
                   15204:          $id.'.PlotType'   => 'XY',
                   15205:          );
                   15206:     #
                   15207:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15208:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15209:     }
                   15210:     #
                   15211:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15212:         return '';
                   15213:     }
                   15214:     my $NumSets=1;
1.138     matthew  15215:     foreach my $array (@{$Ydata}){
1.137     matthew  15216:         next if (! ref($array));
                   15217:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15218:     }
1.138     matthew  15219:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15220:     #
                   15221:     # Deal with other parameters
                   15222:     while (my ($key,$value) = each(%Values)) {
                   15223:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15224:     }
                   15225:     #
1.646     raeburn  15226:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15227:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15228: }
                   15229: 
                   15230: ############################################################
                   15231: ############################################################
                   15232: 
                   15233: =pod
                   15234: 
1.648     raeburn  15235: =item * &DrawXYYGraph()
1.138     matthew  15236: 
                   15237: Facilitates the plotting of data in an XY graph with two Y axes.
                   15238: Puts plot definition data into the users environment in order for 
                   15239: graph.png to plot it.  Returns an <img> tag for the plot.
                   15240: 
                   15241: Inputs:
                   15242: 
                   15243: =over 4
                   15244: 
                   15245: =item $Title: string, the title of the plot
                   15246: 
                   15247: =item $xlabel: string, text describing the X-axis of the plot
                   15248: 
                   15249: =item $ylabel: string, text describing the Y-axis of the plot
                   15250: 
                   15251: =item $colors: Array ref containing the hex color codes for the data to be 
                   15252: plotted in.  If undefined, default values will be used.
                   15253: 
                   15254: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15255: 
                   15256: =item $Ydata1: The first data set
                   15257: 
                   15258: =item $Min1: The minimum value of the left Y-axis
                   15259: 
                   15260: =item $Max1: The maximum value of the left Y-axis
                   15261: 
                   15262: =item $Ydata2: The second data set
                   15263: 
                   15264: =item $Min2: The minimum value of the right Y-axis
                   15265: 
                   15266: =item $Max2: The maximum value of the left Y-axis
                   15267: 
                   15268: =item %Values: hash indicating or overriding any default values which are 
                   15269: passed to graph.png.  
                   15270: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15271: 
                   15272: =back
                   15273: 
                   15274: Returns:
                   15275: 
                   15276: An <img> tag which references graph.png and the appropriate identifying
                   15277: information for the plot.
1.136     matthew  15278: 
                   15279: =cut
                   15280: 
                   15281: ############################################################
                   15282: ############################################################
1.137     matthew  15283: sub DrawXYYGraph {
                   15284:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15285:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15286:     #
                   15287:     # Create the identifier for the graph
                   15288:     my $identifier = &get_cgi_id();
                   15289:     my $id = 'cgi.'.$identifier;
                   15290:     #
                   15291:     $Title  = '' if (! defined($Title));
                   15292:     $xlabel = '' if (! defined($xlabel));
                   15293:     $ylabel = '' if (! defined($ylabel));
                   15294:     my %ValuesHash = 
                   15295:         (
1.369     www      15296:          $id.'.title'  => &escape($Title),
                   15297:          $id.'.xlabel' => &escape($xlabel),
                   15298:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15299:          $id.'.labels' => join(',',@$Xlabels),
                   15300:          $id.'.PlotType' => 'XY',
                   15301:          $id.'.NumSets' => 2,
1.137     matthew  15302:          $id.'.two_axes' => 1,
                   15303:          $id.'.y1_max_value' => $Max1,
                   15304:          $id.'.y1_min_value' => $Min1,
                   15305:          $id.'.y2_max_value' => $Max2,
                   15306:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15307:          );
                   15308:     #
1.137     matthew  15309:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15310:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15311:     }
                   15312:     #
                   15313:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15314:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15315:         return '';
                   15316:     }
                   15317:     my $NumSets=1;
1.137     matthew  15318:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15319:         next if (! ref($array));
                   15320:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15321:     }
                   15322:     #
                   15323:     # Deal with other parameters
                   15324:     while (my ($key,$value) = each(%Values)) {
                   15325:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15326:     }
                   15327:     #
1.646     raeburn  15328:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15329:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15330: }
                   15331: 
                   15332: ############################################################
                   15333: ############################################################
                   15334: 
                   15335: =pod
                   15336: 
1.157     matthew  15337: =back 
                   15338: 
1.139     matthew  15339: =head1 Statistics helper routines?  
                   15340: 
                   15341: Bad place for them but what the hell.
                   15342: 
1.157     matthew  15343: =over 4
                   15344: 
1.648     raeburn  15345: =item * &chartlink()
1.139     matthew  15346: 
                   15347: Returns a link to the chart for a specific student.  
                   15348: 
                   15349: Inputs:
                   15350: 
                   15351: =over 4
                   15352: 
                   15353: =item $linktext: The text of the link
                   15354: 
                   15355: =item $sname: The students username
                   15356: 
                   15357: =item $sdomain: The students domain
                   15358: 
                   15359: =back
                   15360: 
1.157     matthew  15361: =back
                   15362: 
1.139     matthew  15363: =cut
                   15364: 
                   15365: ############################################################
                   15366: ############################################################
                   15367: sub chartlink {
                   15368:     my ($linktext, $sname, $sdomain) = @_;
                   15369:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15370:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15371:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15372:        '">'.$linktext.'</a>';
1.153     matthew  15373: }
                   15374: 
                   15375: #######################################################
                   15376: #######################################################
                   15377: 
                   15378: =pod
                   15379: 
                   15380: =head1 Course Environment Routines
1.157     matthew  15381: 
                   15382: =over 4
1.153     matthew  15383: 
1.648     raeburn  15384: =item * &restore_course_settings()
1.153     matthew  15385: 
1.648     raeburn  15386: =item * &store_course_settings()
1.153     matthew  15387: 
                   15388: Restores/Store indicated form parameters from the course environment.
                   15389: Will not overwrite existing values of the form parameters.
                   15390: 
                   15391: Inputs: 
                   15392: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15393: 
                   15394: a hash ref describing the data to be stored.  For example:
                   15395:    
                   15396: %Save_Parameters = ('Status' => 'scalar',
                   15397:     'chartoutputmode' => 'scalar',
                   15398:     'chartoutputdata' => 'scalar',
                   15399:     'Section' => 'array',
1.373     raeburn  15400:     'Group' => 'array',
1.153     matthew  15401:     'StudentData' => 'array',
                   15402:     'Maps' => 'array');
                   15403: 
                   15404: Returns: both routines return nothing
                   15405: 
1.631     raeburn  15406: =back
                   15407: 
1.153     matthew  15408: =cut
                   15409: 
                   15410: #######################################################
                   15411: #######################################################
                   15412: sub store_course_settings {
1.496     albertel 15413:     return &store_settings($env{'request.course.id'},@_);
                   15414: }
                   15415: 
                   15416: sub store_settings {
1.153     matthew  15417:     # save to the environment
                   15418:     # appenv the same items, just to be safe
1.300     albertel 15419:     my $udom  = $env{'user.domain'};
                   15420:     my $uname = $env{'user.name'};
1.496     albertel 15421:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15422:     my %SaveHash;
                   15423:     my %AppHash;
                   15424:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15425:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15426:         my $envname = 'environment.'.$basename;
1.258     albertel 15427:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15428:             # Save this value away
                   15429:             if ($type eq 'scalar' &&
1.258     albertel 15430:                 (! exists($env{$envname}) || 
                   15431:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15432:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15433:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15434:             } elsif ($type eq 'array') {
                   15435:                 my $stored_form;
1.258     albertel 15436:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15437:                     $stored_form = join(',',
                   15438:                                         map {
1.369     www      15439:                                             &escape($_);
1.258     albertel 15440:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15441:                 } else {
                   15442:                     $stored_form = 
1.369     www      15443:                         &escape($env{'form.'.$setting});
1.153     matthew  15444:                 }
                   15445:                 # Determine if the array contents are the same.
1.258     albertel 15446:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15447:                     $SaveHash{$basename} = $stored_form;
                   15448:                     $AppHash{$envname}   = $stored_form;
                   15449:                 }
                   15450:             }
                   15451:         }
                   15452:     }
                   15453:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15454:                                           $udom,$uname);
1.153     matthew  15455:     if ($put_result !~ /^(ok|delayed)/) {
                   15456:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15457:                                  'got error:'.$put_result);
                   15458:     }
                   15459:     # Make sure these settings stick around in this session, too
1.646     raeburn  15460:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15461:     return;
                   15462: }
                   15463: 
                   15464: sub restore_course_settings {
1.499     albertel 15465:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15466: }
                   15467: 
                   15468: sub restore_settings {
                   15469:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15470:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15471:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15472:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15473:             '.'.$setting;
1.258     albertel 15474:         if (exists($env{$envname})) {
1.153     matthew  15475:             if ($type eq 'scalar') {
1.258     albertel 15476:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15477:             } elsif ($type eq 'array') {
1.258     albertel 15478:                 $env{'form.'.$setting} = [ 
1.153     matthew  15479:                                            map { 
1.369     www      15480:                                                &unescape($_); 
1.258     albertel 15481:                                            } split(',',$env{$envname})
1.153     matthew  15482:                                            ];
                   15483:             }
                   15484:         }
                   15485:     }
1.127     matthew  15486: }
                   15487: 
1.618     raeburn  15488: #######################################################
                   15489: #######################################################
                   15490: 
                   15491: =pod
                   15492: 
                   15493: =head1 Domain E-mail Routines  
                   15494: 
                   15495: =over 4
                   15496: 
1.648     raeburn  15497: =item * &build_recipient_list()
1.618     raeburn  15498: 
1.1144    raeburn  15499: Build recipient lists for following types of e-mail:
1.766     raeburn  15500: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15501: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15502: module change checking, student/employee ID conflict checks, as
                   15503: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15504: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15505: 
                   15506: Inputs:
1.619     raeburn  15507: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15508: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15509: requestsmail, updatesmail, or idconflictsmail).
                   15510: 
1.619     raeburn  15511: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15512: 
1.619     raeburn  15513: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15514: i.e., predates configuration by DC via domainprefs.pm
                   15515: 
                   15516: $requname username of requester (if mailing type is helpdeskmail)
                   15517: 
                   15518: $requdom domain of requester (if mailing type is helpdeskmail)
                   15519: 
                   15520: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15521: 
1.618     raeburn  15522: 
1.655     raeburn  15523: Returns: comma separated list of addresses to which to send e-mail.
                   15524: 
                   15525: =back
1.618     raeburn  15526: 
                   15527: =cut
                   15528: 
                   15529: ############################################################
                   15530: ############################################################
                   15531: sub build_recipient_list {
1.1297    raeburn  15532:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15533:     my @recipients;
1.1270    raeburn  15534:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15535:     my %domconfig =
1.1270    raeburn  15536:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15537:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15538:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15539:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15540:                 my @contacts = ('adminemail','supportemail');
                   15541:                 foreach my $item (@contacts) {
                   15542:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15543:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15544:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15545:                             push(@recipients,$addr);
                   15546:                         }
1.619     raeburn  15547:                     }
1.1270    raeburn  15548:                 }
                   15549:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15550:                 if ($mailing eq 'helpdeskmail') {
                   15551:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15552:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15553:                         my @ok_bccs;
                   15554:                         foreach my $bcc (@bccs) {
                   15555:                             $bcc =~ s/^\s+//g;
                   15556:                             $bcc =~ s/\s+$//g;
                   15557:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15558:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15559:                                     push(@ok_bccs,$bcc);
                   15560:                                 }
                   15561:                             }
                   15562:                         }
                   15563:                         if (@ok_bccs > 0) {
                   15564:                             $allbcc = join(', ',@ok_bccs);
                   15565:                         }
                   15566:                     }
                   15567:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15568:                 }
                   15569:             }
1.766     raeburn  15570:         } elsif ($origmail ne '') {
1.1270    raeburn  15571:             $lastresort = $origmail;
1.618     raeburn  15572:         }
1.1297    raeburn  15573:         if ($mailing eq 'helpdeskmail') {
                   15574:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15575:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15576:                 my ($inststatus,$inststatus_checked);
                   15577:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15578:                     ($env{'user.domain'} ne 'public')) {
                   15579:                     $inststatus_checked = 1;
                   15580:                     $inststatus = $env{'environment.inststatus'};
                   15581:                 }
                   15582:                 unless ($inststatus_checked) {
                   15583:                     if (($requname ne '') && ($requdom ne '')) {
                   15584:                         if (($requname =~ /^$match_username$/) &&
                   15585:                             ($requdom =~ /^$match_domain$/) &&
                   15586:                             (&Apache::lonnet::domain($requdom))) {
                   15587:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15588:                                                                       $requdom);
                   15589:                             unless ($requhome eq 'no_host') {
                   15590:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15591:                                 $inststatus = $userenv{'inststatus'};
                   15592:                                 $inststatus_checked = 1;
                   15593:                             }
                   15594:                         }
                   15595:                     }
                   15596:                 }
                   15597:                 unless ($inststatus_checked) {
                   15598:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15599:                         my %srch = (srchby     => 'email',
                   15600:                                     srchdomain => $defdom,
                   15601:                                     srchterm   => $reqemail,
                   15602:                                     srchtype   => 'exact');
                   15603:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15604:                         foreach my $uname (keys(%srch_results)) {
                   15605:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15606:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15607:                                 $inststatus_checked = 1;
                   15608:                                 last;
                   15609:                             }
                   15610:                         }
                   15611:                         unless ($inststatus_checked) {
                   15612:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15613:                             if ($dirsrchres eq 'ok') {
                   15614:                                 foreach my $uname (keys(%srch_results)) {
                   15615:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15616:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15617:                                         $inststatus_checked = 1;
                   15618:                                         last;
                   15619:                                     }
                   15620:                                 }
                   15621:                             }
                   15622:                         }
                   15623:                     }
                   15624:                 }
                   15625:                 if ($inststatus ne '') {
                   15626:                     foreach my $status (split(/\:/,$inststatus)) {
                   15627:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15628:                             my @contacts = ('adminemail','supportemail');
                   15629:                             foreach my $item (@contacts) {
                   15630:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15631:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15632:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15633:                                         push(@recipients,$addr);
                   15634:                                     }
                   15635:                                 }
                   15636:                             }
                   15637:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15638:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15639:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15640:                                 my @ok_bccs;
                   15641:                                 foreach my $bcc (@bccs) {
                   15642:                                     $bcc =~ s/^\s+//g;
                   15643:                                     $bcc =~ s/\s+$//g;
                   15644:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15645:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15646:                                             push(@ok_bccs,$bcc);
                   15647:                                         }
                   15648:                                     }
                   15649:                                 }
                   15650:                                 if (@ok_bccs > 0) {
                   15651:                                     $allbcc = join(', ',@ok_bccs);
                   15652:                                 }
                   15653:                             }
                   15654:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15655:                             last;
                   15656:                         }
                   15657:                     }
                   15658:                 }
                   15659:             }
                   15660:         }
1.619     raeburn  15661:     } elsif ($origmail ne '') {
1.1270    raeburn  15662:         $lastresort = $origmail;
                   15663:     }
1.1297    raeburn  15664:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15665:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15666:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15667:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15668:             my %what = (
                   15669:                           perlvar => 1,
                   15670:                        );
                   15671:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15672:             if ($primary) {
                   15673:                 my $gotaddr;
                   15674:                 my ($result,$returnhash) =
                   15675:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15676:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15677:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15678:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15679:                         $gotaddr = 1;
                   15680:                     }
                   15681:                 }
                   15682:                 unless ($gotaddr) {
                   15683:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15684:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15685:                     unless ($uintdom eq $intdom) {
                   15686:                         my %domconfig =
                   15687:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15688:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15689:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15690:                                 my @contacts = ('adminemail','supportemail');
                   15691:                                 foreach my $item (@contacts) {
                   15692:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15693:                                         my $addr = $domconfig{'contacts'}{$item};
                   15694:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15695:                                             push(@recipients,$addr);
                   15696:                                         }
                   15697:                                     }
                   15698:                                 }
                   15699:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15700:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15701:                                 }
                   15702:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15703:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15704:                                     my @ok_bccs;
                   15705:                                     foreach my $bcc (@bccs) {
                   15706:                                         $bcc =~ s/^\s+//g;
                   15707:                                         $bcc =~ s/\s+$//g;
                   15708:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15709:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15710:                                                 push(@ok_bccs,$bcc);
                   15711:                                             }
                   15712:                                         }
                   15713:                                     }
                   15714:                                     if (@ok_bccs > 0) {
                   15715:                                         $allbcc = join(', ',@ok_bccs);
                   15716:                                     }
                   15717:                                 }
                   15718:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15719:                             }
                   15720:                         }
                   15721:                     }
                   15722:                 }
                   15723:             }
                   15724:         }
1.618     raeburn  15725:     }
1.688     raeburn  15726:     if (defined($defmail)) {
                   15727:         if ($defmail ne '') {
                   15728:             push(@recipients,$defmail);
                   15729:         }
1.618     raeburn  15730:     }
                   15731:     if ($otheremails) {
1.619     raeburn  15732:         my @others;
                   15733:         if ($otheremails =~ /,/) {
                   15734:             @others = split(/,/,$otheremails);
1.618     raeburn  15735:         } else {
1.619     raeburn  15736:             push(@others,$otheremails);
                   15737:         }
                   15738:         foreach my $addr (@others) {
                   15739:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15740:                 push(@recipients,$addr);
                   15741:             }
1.618     raeburn  15742:         }
                   15743:     }
1.1298    raeburn  15744:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15745:         if ((!@recipients) && ($lastresort ne '')) {
                   15746:             push(@recipients,$lastresort);
                   15747:         }
                   15748:     } elsif ($lastresort ne '') {
                   15749:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15750:             push(@recipients,$lastresort);
                   15751:         }
                   15752:     }
1.1271    raeburn  15753:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15754:     if (wantarray) {
                   15755:         return ($recipientlist,$allbcc,$addtext);
                   15756:     } else {
                   15757:         return $recipientlist;
                   15758:     }
1.618     raeburn  15759: }
                   15760: 
1.127     matthew  15761: ############################################################
                   15762: ############################################################
1.154     albertel 15763: 
1.655     raeburn  15764: =pod
                   15765: 
1.1224    musolffc 15766: =over 4
                   15767: 
1.1223    musolffc 15768: =item * &mime_email()
                   15769: 
                   15770: Sends an email with a possible attachment
                   15771: 
                   15772: Inputs:
                   15773: 
                   15774: =over 4
                   15775: 
                   15776: from -              Sender's email address
                   15777: 
1.1343    raeburn  15778: replyto -           Reply-To email address
                   15779: 
1.1223    musolffc 15780: to -                Email address of recipient
                   15781: 
                   15782: subject -           Subject of email
                   15783: 
                   15784: body -              Body of email
                   15785: 
                   15786: cc_string -         Carbon copy email address
                   15787: 
                   15788: bcc -               Blind carbon copy email address
                   15789: 
                   15790: attachment_path -   Path of file to be attached
                   15791: 
                   15792: file_name -         Name of file to be attached
                   15793: 
                   15794: attachment_text -   The body of an attachment of type "TEXT"
                   15795: 
                   15796: =back
                   15797: 
                   15798: =back
                   15799: 
                   15800: =cut
                   15801: 
                   15802: ############################################################
                   15803: ############################################################
                   15804: 
                   15805: sub mime_email {
1.1343    raeburn  15806:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15807:         $file_name,$attachment_text) = @_;
                   15808:  
1.1223    musolffc 15809:     my $msg = MIME::Lite->new(
                   15810:              From    => $from,
                   15811:              To      => $to,
                   15812:              Subject => $subject,
                   15813:              Type    =>'TEXT',
                   15814:              Data    => $body,
                   15815:              );
1.1343    raeburn  15816:     if ($replyto ne '') {
                   15817:         $msg->add("Reply-To" => $replyto);
                   15818:     }
1.1223    musolffc 15819:     if ($cc_string ne '') {
                   15820:         $msg->add("Cc" => $cc_string);
                   15821:     }
                   15822:     if ($bcc ne '') {
                   15823:         $msg->add("Bcc" => $bcc);
                   15824:     }
                   15825:     $msg->attr("content-type"         => "text/plain");
                   15826:     $msg->attr("content-type.charset" => "UTF-8");
                   15827:     # Attach file if given
                   15828:     if ($attachment_path) {
                   15829:         unless ($file_name) {
                   15830:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15831:         }
                   15832:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15833:         $msg->attach(Type     => $type,
                   15834:                      Path     => $attachment_path,
                   15835:                      Filename => $file_name
                   15836:                      );
                   15837:     # Otherwise attach text if given
                   15838:     } elsif ($attachment_text) {
                   15839:         $msg->attach(Type => 'TEXT',
                   15840:                      Data => $attachment_text);
                   15841:     }
                   15842:     # Send it
                   15843:     $msg->send('sendmail');
                   15844: }
                   15845: 
                   15846: ############################################################
                   15847: ############################################################
                   15848: 
                   15849: =pod
                   15850: 
1.655     raeburn  15851: =head1 Course Catalog Routines
                   15852: 
                   15853: =over 4
                   15854: 
                   15855: =item * &gather_categories()
                   15856: 
                   15857: Converts category definitions - keys of categories hash stored in  
                   15858: coursecategories in configuration.db on the primary library server in a 
                   15859: domain - to an array.  Also generates javascript and idx hash used to 
                   15860: generate Domain Coordinator interface for editing Course Categories.
                   15861: 
                   15862: Inputs:
1.663     raeburn  15863: 
1.655     raeburn  15864: categories (reference to hash of category definitions).
1.663     raeburn  15865: 
1.655     raeburn  15866: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15867:       categories and subcategories).
1.663     raeburn  15868: 
1.655     raeburn  15869: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15870:       editing Course Categories).
1.663     raeburn  15871: 
1.655     raeburn  15872: jsarray (reference to array of categories used to create Javascript arrays for
                   15873:          Domain Coordinator interface for editing Course Categories).
                   15874: 
                   15875: Returns: nothing
                   15876: 
                   15877: Side effects: populates cats, idx and jsarray. 
                   15878: 
                   15879: =cut
                   15880: 
                   15881: sub gather_categories {
                   15882:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15883:     my %counters;
                   15884:     my $num = 0;
                   15885:     foreach my $item (keys(%{$categories})) {
                   15886:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15887:         if ($container eq '' && $depth == 0) {
                   15888:             $cats->[$depth][$categories->{$item}] = $cat;
                   15889:         } else {
                   15890:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15891:         }
                   15892:         my ($escitem,$tail) = split(/:/,$item,2);
                   15893:         if ($counters{$tail} eq '') {
                   15894:             $counters{$tail} = $num;
                   15895:             $num ++;
                   15896:         }
                   15897:         if (ref($idx) eq 'HASH') {
                   15898:             $idx->{$item} = $counters{$tail};
                   15899:         }
                   15900:         if (ref($jsarray) eq 'ARRAY') {
                   15901:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15902:         }
                   15903:     }
                   15904:     return;
                   15905: }
                   15906: 
                   15907: =pod
                   15908: 
                   15909: =item * &extract_categories()
                   15910: 
                   15911: Used to generate breadcrumb trails for course categories.
                   15912: 
                   15913: Inputs:
1.663     raeburn  15914: 
1.655     raeburn  15915: categories (reference to hash of category definitions).
1.663     raeburn  15916: 
1.655     raeburn  15917: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15918:       categories and subcategories).
1.663     raeburn  15919: 
1.655     raeburn  15920: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15921: 
1.655     raeburn  15922: allitems (reference to hash - key is category key 
                   15923:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15924: 
1.655     raeburn  15925: idx (reference to hash of counters used in Domain Coordinator interface for
                   15926:       editing Course Categories).
1.663     raeburn  15927: 
1.655     raeburn  15928: jsarray (reference to array of categories used to create Javascript arrays for
                   15929:          Domain Coordinator interface for editing Course Categories).
                   15930: 
1.665     raeburn  15931: subcats (reference to hash of arrays containing all subcategories within each 
                   15932:          category, -recursive)
                   15933: 
1.1321    raeburn  15934: maxd (reference to hash used to hold max depth for all top-level categories).
                   15935: 
1.655     raeburn  15936: Returns: nothing
                   15937: 
                   15938: Side effects: populates trails and allitems hash references.
                   15939: 
                   15940: =cut
                   15941: 
                   15942: sub extract_categories {
1.1321    raeburn  15943:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15944:     if (ref($categories) eq 'HASH') {
                   15945:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15946:         if (ref($cats->[0]) eq 'ARRAY') {
                   15947:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15948:                 my $name = $cats->[0][$i];
                   15949:                 my $item = &escape($name).'::0';
                   15950:                 my $trailstr;
                   15951:                 if ($name eq 'instcode') {
                   15952:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15953:                 } elsif ($name eq 'communities') {
                   15954:                     $trailstr = &mt('Communities');
1.1239    raeburn  15955:                 } elsif ($name eq 'placement') {
                   15956:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15957:                 } else {
                   15958:                     $trailstr = $name;
                   15959:                 }
                   15960:                 if ($allitems->{$item} eq '') {
                   15961:                     push(@{$trails},$trailstr);
                   15962:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15963:                 }
                   15964:                 my @parents = ($name);
                   15965:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15966:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15967:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15968:                         if (ref($subcats) eq 'HASH') {
                   15969:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15970:                         }
1.1321    raeburn  15971:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15972:                     }
                   15973:                 } else {
                   15974:                     if (ref($subcats) eq 'HASH') {
                   15975:                         $subcats->{$item} = [];
1.655     raeburn  15976:                     }
1.1321    raeburn  15977:                     if (ref($maxd) eq 'HASH') {
                   15978:                         $maxd->{$name} = 1;
                   15979:                     }
1.655     raeburn  15980:                 }
                   15981:             }
                   15982:         }
                   15983:     }
                   15984:     return;
                   15985: }
                   15986: 
                   15987: =pod
                   15988: 
1.1162    raeburn  15989: =item * &recurse_categories()
1.655     raeburn  15990: 
                   15991: Recursively used to generate breadcrumb trails for course categories.
                   15992: 
                   15993: Inputs:
1.663     raeburn  15994: 
1.655     raeburn  15995: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15996:       categories and subcategories).
1.663     raeburn  15997: 
1.655     raeburn  15998: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15999: 
                   16000: category (current course category, for which breadcrumb trail is being generated).
                   16001: 
                   16002: trails (reference to array of breadcrumb trails for each category).
                   16003: 
1.655     raeburn  16004: allitems (reference to hash - key is category key
                   16005:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16006: 
1.655     raeburn  16007: parents (array containing containers directories for current category, 
                   16008:          back to top level). 
                   16009: 
                   16010: Returns: nothing
                   16011: 
                   16012: Side effects: populates trails and allitems hash references
                   16013: 
                   16014: =cut
                   16015: 
                   16016: sub recurse_categories {
1.1321    raeburn  16017:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16018:     my $shallower = $depth - 1;
                   16019:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16020:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16021:             my $name = $cats->[$depth]{$category}[$k];
                   16022:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16023:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16024:             if ($allitems->{$item} eq '') {
                   16025:                 push(@{$trails},$trailstr);
                   16026:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16027:             }
                   16028:             my $deeper = $depth+1;
                   16029:             push(@{$parents},$category);
1.665     raeburn  16030:             if (ref($subcats) eq 'HASH') {
                   16031:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16032:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16033:                     my $higher;
                   16034:                     if ($j > 0) {
                   16035:                         $higher = &escape($parents->[$j]).':'.
                   16036:                                   &escape($parents->[$j-1]).':'.$j;
                   16037:                     } else {
                   16038:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16039:                     }
                   16040:                     push(@{$subcats->{$higher}},$subcat);
                   16041:                 }
                   16042:             }
                   16043:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16044:                                 $subcats,$maxd);
1.655     raeburn  16045:             pop(@{$parents});
                   16046:         }
                   16047:     } else {
                   16048:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16049:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16050:         if ($allitems->{$item} eq '') {
                   16051:             push(@{$trails},$trailstr);
                   16052:             $allitems->{$item} = scalar(@{$trails})-1;
                   16053:         }
1.1321    raeburn  16054:         if (ref($maxd) eq 'HASH') {
                   16055:             if ($depth > $maxd->{$parents->[0]}) {
                   16056:                 $maxd->{$parents->[0]} = $depth;
                   16057:             }
                   16058:         }
1.655     raeburn  16059:     }
                   16060:     return;
                   16061: }
                   16062: 
1.663     raeburn  16063: =pod
                   16064: 
1.1162    raeburn  16065: =item * &assign_categories_table()
1.663     raeburn  16066: 
                   16067: Create a datatable for display of hierarchical categories in a domain,
                   16068: with checkboxes to allow a course to be categorized. 
                   16069: 
                   16070: Inputs:
                   16071: 
                   16072: cathash - reference to hash of categories defined for the domain (from
                   16073:           configuration.db)
                   16074: 
                   16075: currcat - scalar with an & separated list of categories assigned to a course. 
                   16076: 
1.919     raeburn  16077: type    - scalar contains course type (Course or Community).
                   16078: 
1.1260    raeburn  16079: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16080:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16081: 
1.663     raeburn  16082: Returns: $output (markup to be displayed) 
                   16083: 
                   16084: =cut
                   16085: 
                   16086: sub assign_categories_table {
1.1259    raeburn  16087:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16088:     my $output;
                   16089:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16090:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16091:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16092:         $maxdepth = scalar(@cats);
                   16093:         if (@cats > 0) {
                   16094:             my $itemcount = 0;
                   16095:             if (ref($cats[0]) eq 'ARRAY') {
                   16096:                 my @currcategories;
                   16097:                 if ($currcat ne '') {
                   16098:                     @currcategories = split('&',$currcat);
                   16099:                 }
1.919     raeburn  16100:                 my $table;
1.663     raeburn  16101:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16102:                     my $parent = $cats[0][$i];
1.919     raeburn  16103:                     next if ($parent eq 'instcode');
                   16104:                     if ($type eq 'Community') {
                   16105:                         next unless ($parent eq 'communities');
1.1239    raeburn  16106:                     } elsif ($type eq 'Placement') {
                   16107:                         next unless ($parent eq 'placement');
1.919     raeburn  16108:                     } else {
1.1239    raeburn  16109:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16110:                     }
1.663     raeburn  16111:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16112:                     my $item = &escape($parent).'::0';
                   16113:                     my $checked = '';
                   16114:                     if (@currcategories > 0) {
                   16115:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16116:                             $checked = ' checked="checked"';
1.663     raeburn  16117:                         }
                   16118:                     }
1.919     raeburn  16119:                     my $parent_title = $parent;
                   16120:                     if ($parent eq 'communities') {
                   16121:                         $parent_title = &mt('Communities');
1.1239    raeburn  16122:                     } elsif ($parent eq 'placement') {
                   16123:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16124:                     }
                   16125:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16126:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16127:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16128:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16129:                     my $depth = 1;
                   16130:                     push(@path,$parent);
1.1259    raeburn  16131:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16132:                     pop(@path);
1.919     raeburn  16133:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16134:                     $itemcount ++;
                   16135:                 }
1.919     raeburn  16136:                 if ($itemcount) {
                   16137:                     $output = &Apache::loncommon::start_data_table().
                   16138:                               $table.
                   16139:                               &Apache::loncommon::end_data_table();
                   16140:                 }
1.663     raeburn  16141:             }
                   16142:         }
                   16143:     }
                   16144:     return $output;
                   16145: }
                   16146: 
                   16147: =pod
                   16148: 
1.1162    raeburn  16149: =item * &assign_category_rows()
1.663     raeburn  16150: 
                   16151: Create a datatable row for display of nested categories in a domain,
                   16152: with checkboxes to allow a course to be categorized,called recursively.
                   16153: 
                   16154: Inputs:
                   16155: 
                   16156: itemcount - track row number for alternating colors
                   16157: 
                   16158: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16159:       categories and subcategories.
                   16160: 
                   16161: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16162: 
                   16163: parent - parent of current category item
                   16164: 
                   16165: path - Array containing all categories back up through the hierarchy from the
                   16166:        current category to the top level.
                   16167: 
                   16168: currcategories - reference to array of current categories assigned to the course
                   16169: 
1.1260    raeburn  16170: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16171:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16172: 
1.663     raeburn  16173: Returns: $output (markup to be displayed).
                   16174: 
                   16175: =cut
                   16176: 
                   16177: sub assign_category_rows {
1.1259    raeburn  16178:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16179:     my ($text,$name,$item,$chgstr);
                   16180:     if (ref($cats) eq 'ARRAY') {
                   16181:         my $maxdepth = scalar(@{$cats});
                   16182:         if (ref($cats->[$depth]) eq 'HASH') {
                   16183:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16184:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16185:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16186:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16187:                 for (my $j=0; $j<$numchildren; $j++) {
                   16188:                     $name = $cats->[$depth]{$parent}[$j];
                   16189:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16190:                     my $deeper = $depth+1;
                   16191:                     my $checked = '';
                   16192:                     if (ref($currcategories) eq 'ARRAY') {
                   16193:                         if (@{$currcategories} > 0) {
                   16194:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16195:                                 $checked = ' checked="checked"';
1.663     raeburn  16196:                             }
                   16197:                         }
                   16198:                     }
1.664     raeburn  16199:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16200:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16201:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16202:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16203:                              '</td><td>';
1.663     raeburn  16204:                     if (ref($path) eq 'ARRAY') {
                   16205:                         push(@{$path},$name);
1.1259    raeburn  16206:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16207:                         pop(@{$path});
                   16208:                     }
                   16209:                     $text .= '</td></tr>';
                   16210:                 }
                   16211:                 $text .= '</table></td>';
                   16212:             }
                   16213:         }
                   16214:     }
                   16215:     return $text;
                   16216: }
                   16217: 
1.1181    raeburn  16218: =pod
                   16219: 
                   16220: =back
                   16221: 
                   16222: =cut
                   16223: 
1.655     raeburn  16224: ############################################################
                   16225: ############################################################
                   16226: 
                   16227: 
1.443     albertel 16228: sub commit_customrole {
1.664     raeburn  16229:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16230:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16231:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16232:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16233:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16234:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16235:                  '</b><br />';
                   16236:     return $output;
                   16237: }
                   16238: 
                   16239: sub commit_standardrole {
1.1116    raeburn  16240:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16241:     my ($output,$logmsg,$linefeed);
                   16242:     if ($context eq 'auto') {
                   16243:         $linefeed = "\n";
                   16244:     } else {
                   16245:         $linefeed = "<br />\n";
                   16246:     }  
1.443     albertel 16247:     if ($three eq 'st') {
1.541     raeburn  16248:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  16249:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16250:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16251:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16252:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16253:         } else {
1.541     raeburn  16254:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16255:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16256:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16257:             if ($context eq 'auto') {
                   16258:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16259:             } else {
                   16260:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16261:                &mt('Add to classlist').': <b>ok</b>';
                   16262:             }
                   16263:             $output .= $linefeed;
1.443     albertel 16264:         }
                   16265:     } else {
                   16266:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16267:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16268:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16269:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16270:         if ($context eq 'auto') {
                   16271:             $output .= $result.$linefeed;
                   16272:         } else {
                   16273:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16274:         }
1.443     albertel 16275:     }
                   16276:     return $output;
                   16277: }
                   16278: 
                   16279: sub commit_studentrole {
1.1116    raeburn  16280:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16281:         $credits) = @_;
1.626     raeburn  16282:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16283:     if ($context eq 'auto') {
                   16284:         $linefeed = "\n";
                   16285:     } else {
                   16286:         $linefeed = '<br />'."\n";
                   16287:     }
1.443     albertel 16288:     if (defined($one) && defined($two)) {
                   16289:         my $cid=$one.'_'.$two;
                   16290:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16291:         my $secchange = 0;
                   16292:         my $expire_role_result;
                   16293:         my $modify_section_result;
1.628     raeburn  16294:         if ($oldsec ne '-1') { 
                   16295:             if ($oldsec ne $sec) {
1.443     albertel 16296:                 $secchange = 1;
1.628     raeburn  16297:                 my $now = time;
1.443     albertel 16298:                 my $uurl='/'.$cid;
                   16299:                 $uurl=~s/\_/\//g;
                   16300:                 if ($oldsec) {
                   16301:                     $uurl.='/'.$oldsec;
                   16302:                 }
1.626     raeburn  16303:                 $oldsecurl = $uurl;
1.628     raeburn  16304:                 $expire_role_result = 
1.652     raeburn  16305:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16306:                 if ($env{'request.course.sec'} ne '') { 
                   16307:                     if ($expire_role_result eq 'refused') {
                   16308:                         my @roles = ('st');
                   16309:                         my @statuses = ('previous');
                   16310:                         my @roledoms = ($one);
                   16311:                         my $withsec = 1;
                   16312:                         my %roleshash = 
                   16313:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16314:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16315:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16316:                             my ($oldstart,$oldend) = 
                   16317:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16318:                             if ($oldend > 0 && $oldend <= $now) {
                   16319:                                 $expire_role_result = 'ok';
                   16320:                             }
                   16321:                         }
                   16322:                     }
                   16323:                 }
1.443     albertel 16324:                 $result = $expire_role_result;
                   16325:             }
                   16326:         }
                   16327:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16328:             $modify_section_result = 
                   16329:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16330:                                                            undef,undef,undef,$sec,
                   16331:                                                            $end,$start,'','',$cid,
                   16332:                                                            '',$context,$credits);
1.443     albertel 16333:             if ($modify_section_result =~ /^ok/) {
                   16334:                 if ($secchange == 1) {
1.628     raeburn  16335:                     if ($sec eq '') {
                   16336:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16337:                     } else {
                   16338:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16339:                     }
1.443     albertel 16340:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16341:                     if ($sec eq '') {
                   16342:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16343:                     } else {
                   16344:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16345:                     }
1.443     albertel 16346:                 } else {
1.628     raeburn  16347:                     if ($sec eq '') {
                   16348:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16349:                     } else {
                   16350:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16351:                     }
1.443     albertel 16352:                 }
                   16353:             } else {
1.1115    raeburn  16354:                 if ($secchange) { 
1.628     raeburn  16355:                     $$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;
                   16356:                 } else {
                   16357:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16358:                 }
1.443     albertel 16359:             }
                   16360:             $result = $modify_section_result;
                   16361:         } elsif ($secchange == 1) {
1.628     raeburn  16362:             if ($oldsec eq '') {
1.1103    raeburn  16363:                 $$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  16364:             } else {
                   16365:                 $$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;
                   16366:             }
1.626     raeburn  16367:             if ($expire_role_result eq 'refused') {
                   16368:                 my $newsecurl = '/'.$cid;
                   16369:                 $newsecurl =~ s/\_/\//g;
                   16370:                 if ($sec ne '') {
                   16371:                     $newsecurl.='/'.$sec;
                   16372:                 }
                   16373:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16374:                     if ($sec eq '') {
                   16375:                         $$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;
                   16376:                     } else {
                   16377:                         $$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;
                   16378:                     }
                   16379:                 }
                   16380:             }
1.443     albertel 16381:         }
                   16382:     } else {
1.626     raeburn  16383:         $$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 16384:         $result = "error: incomplete course id\n";
                   16385:     }
                   16386:     return $result;
                   16387: }
                   16388: 
1.1108    raeburn  16389: sub show_role_extent {
                   16390:     my ($scope,$context,$role) = @_;
                   16391:     $scope =~ s{^/}{};
                   16392:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16393:     push(@courseroles,'co');
                   16394:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16395:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16396:         $scope =~ s{/}{_};
                   16397:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16398:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16399:         my ($audom,$auname) = split(/\//,$scope);
                   16400:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16401:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16402:     } else {
                   16403:         $scope =~ s{/$}{};
                   16404:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16405:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16406:     }
                   16407: }
                   16408: 
1.443     albertel 16409: ############################################################
                   16410: ############################################################
                   16411: 
1.566     albertel 16412: sub check_clone {
1.578     raeburn  16413:     my ($args,$linefeed) = @_;
1.566     albertel 16414:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16415:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16416:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16417:     my $clonetitle;
                   16418:     my @clonemsg;
1.566     albertel 16419:     my $can_clone = 0;
1.944     raeburn  16420:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16421:     if ($lctype ne 'community') {
                   16422:         $lctype = 'course';
                   16423:     }
1.566     albertel 16424:     if ($clonehome eq 'no_host') {
1.944     raeburn  16425:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16426:             push(@clonemsg,({
                   16427:                               mt => 'No new community created.',
                   16428:                               args => [],
                   16429:                             },
                   16430:                             {
                   16431:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16432:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16433:                             }));
1.908     raeburn  16434:         } else {
1.1344    raeburn  16435:             push(@clonemsg,({
                   16436:                               mt => 'No new course created.',
                   16437:                               args => [],
                   16438:                             },
                   16439:                             {
                   16440:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16441:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16442:                             }));
                   16443:         }
1.566     albertel 16444:     } else {
                   16445: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16446:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16447:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16448:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16449:                 push(@clonemsg,({
                   16450:                                   mt => 'No new community created.',
                   16451:                                   args => [],
                   16452:                                 },
                   16453:                                 {
                   16454:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16455:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16456:                                 }));
                   16457:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16458:             }
                   16459:         }
1.1262    raeburn  16460: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16461:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16462: 	    $can_clone = 1;
                   16463: 	} else {
1.1221    raeburn  16464: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16465: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16466:             if ($clonehash{'cloners'} eq '') {
                   16467:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16468:                 if ($domdefs{'canclone'}) {
                   16469:                     unless ($domdefs{'canclone'} eq 'none') {
                   16470:                         if ($domdefs{'canclone'} eq 'domain') {
                   16471:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16472:                                 $can_clone = 1;
                   16473:                             }
                   16474:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16475:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16476:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16477:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16478:                                 $can_clone = 1;
                   16479:                             }
                   16480:                         }
                   16481:                     }
                   16482:                 }
1.578     raeburn  16483:             } else {
1.1221    raeburn  16484: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16485:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16486:                     $can_clone = 1;
1.1221    raeburn  16487:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16488:                     $can_clone = 1;
1.1225    raeburn  16489:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16490:                     $can_clone = 1;
1.1221    raeburn  16491:                 }
                   16492:                 unless ($can_clone) {
1.1225    raeburn  16493:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16494:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16495:                         my (%gotdomdefaults,%gotcodedefaults);
                   16496:                         foreach my $cloner (@cloners) {
                   16497:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16498:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16499:                                 my (%codedefaults,@code_order);
                   16500:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16501:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16502:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16503:                                     }
                   16504:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16505:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16506:                                     }
                   16507:                                 } else {
                   16508:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16509:                                                                             \%codedefaults,
                   16510:                                                                             \@code_order);
                   16511:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16512:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16513:                                 }
                   16514:                                 if (@code_order > 0) {
                   16515:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16516:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16517:                                                                                 $args->{'crscode'})) {
                   16518:                                         $can_clone = 1;
                   16519:                                         last;
                   16520:                                     }
                   16521:                                 }
                   16522:                             }
                   16523:                         }
                   16524:                     }
1.1225    raeburn  16525:                 }
                   16526:             }
                   16527:             unless ($can_clone) {
                   16528:                 my $ccrole = 'cc';
                   16529:                 if ($args->{'crstype'} eq 'Community') {
                   16530:                     $ccrole = 'co';
                   16531:                 }
                   16532: 	        my %roleshash =
                   16533: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16534: 					          $args->{'ccdomain'},
                   16535:                                                   'userroles',['active'],[$ccrole],
                   16536: 					          [$args->{'clonedomain'}]);
                   16537: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16538:                     $can_clone = 1;
                   16539:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16540:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16541:                     $can_clone = 1;
1.1221    raeburn  16542:                 }
                   16543:             }
                   16544:             unless ($can_clone) {
                   16545:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16546:                     push(@clonemsg,({
                   16547:                                       mt => 'No new community created.',
                   16548:                                       args => [],
                   16549:                                     },
                   16550:                                     {
                   16551:                                       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]).',
                   16552:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16553:                                     }));
1.942     raeburn  16554:                 } else {
1.1344    raeburn  16555:                     push(@clonemsg,({
                   16556:                                       mt => 'No new course created.',
                   16557:                                       args => [],
                   16558:                                     },
                   16559:                                     {
                   16560:                                       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]).',
                   16561:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16562:                                     }));
1.1221    raeburn  16563:                 }
1.566     albertel 16564: 	    }
1.578     raeburn  16565:         }
1.566     albertel 16566:     }
1.1344    raeburn  16567:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16568: }
                   16569: 
1.444     albertel 16570: sub construct_course {
1.1262    raeburn  16571:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16572:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16573:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16574:     my $linefeed =  '<br />'."\n";
                   16575:     if ($context eq 'auto') {
                   16576:         $linefeed = "\n";
                   16577:     }
1.566     albertel 16578: 
                   16579: #
                   16580: # Are we cloning?
                   16581: #
1.1344    raeburn  16582:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16583:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16584: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16585:         if (!$can_clone) {
1.1344    raeburn  16586: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16587: 	}
                   16588:     }
                   16589: 
1.444     albertel 16590: #
                   16591: # Open course
                   16592: #
1.1239    raeburn  16593:     my $showncrstype;
                   16594:     if ($args->{'crstype'} eq 'Placement') {
                   16595:         $showncrstype = 'placement test'; 
                   16596:     } else {  
                   16597:         $showncrstype = lc($args->{'crstype'});
                   16598:     }
1.444     albertel 16599:     my %cenv=();
                   16600:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16601:                                              $args->{'cdescr'},
                   16602:                                              $args->{'curl'},
                   16603:                                              $args->{'course_home'},
                   16604:                                              $args->{'nonstandard'},
                   16605:                                              $args->{'crscode'},
                   16606:                                              $args->{'ccuname'}.':'.
                   16607:                                              $args->{'ccdomain'},
1.882     raeburn  16608:                                              $args->{'crstype'},
1.1344    raeburn  16609:                                              $cnum,$context,$category,
                   16610:                                              $callercontext);
1.444     albertel 16611: 
                   16612:     # Note: The testing routines depend on this being output; see 
                   16613:     # Utils::Course. This needs to at least be output as a comment
                   16614:     # if anyone ever decides to not show this, and Utils::Course::new
                   16615:     # will need to be suitably modified.
1.1344    raeburn  16616:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16617:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16618:     } else {
                   16619:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16620:     }
1.943     raeburn  16621:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16622:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16623:     }
                   16624: 
1.444     albertel 16625: #
                   16626: # Check if created correctly
                   16627: #
1.479     albertel 16628:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16629:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16630:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16631:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16632:             $outcome .= &mt_user($user_lh,
                   16633:                             'Course creation failed, unrecognized course home server.');
                   16634:         } else {
                   16635:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16636:         }
                   16637:         $outcome .= $linefeed;
                   16638:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16639:     }
1.541     raeburn  16640:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16641: 
1.444     albertel 16642: #
1.566     albertel 16643: # Do the cloning
                   16644: #   
1.1344    raeburn  16645:     my @clonemsg;
1.566     albertel 16646:     if ($can_clone && $cloneid) {
1.1344    raeburn  16647:         push(@clonemsg,
                   16648:                       {
                   16649:                           mt => 'Created [_1] by cloning from [_2]',
                   16650:                           args => [$showncrstype,$clonetitle],
                   16651:                       });
1.566     albertel 16652: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16653: # Copy all files
1.1344    raeburn  16654:         my @info =
                   16655: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16656: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16657:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16658:                                                      $args->{'tinyurls'});
                   16659:         if (@info) {
                   16660:             push(@clonemsg,@info);
                   16661:         }
1.444     albertel 16662: # Restore URL
1.566     albertel 16663: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16664: # Restore title
1.566     albertel 16665: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16666: # Restore creation date, creator and creation context.
                   16667:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16668:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16669:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16670: # Mark as cloned
1.566     albertel 16671: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16672: # Need to clone grading mode
                   16673:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16674:         $cenv{'grading'}=$newenv{'grading'};
                   16675: # Do not clone these environment entries
                   16676:         &Apache::lonnet::del('environment',
                   16677:                   ['default_enrollment_start_date',
                   16678:                    'default_enrollment_end_date',
                   16679:                    'question.email',
                   16680:                    'policy.email',
                   16681:                    'comment.email',
                   16682:                    'pch.users.denied',
1.725     raeburn  16683:                    'plc.users.denied',
                   16684:                    'hidefromcat',
1.1121    raeburn  16685:                    'checkforpriv',
1.1355    raeburn  16686:                    'categories'],
1.638     www      16687:                    $$crsudom,$$crsunum);
1.1170    raeburn  16688:         if ($args->{'textbook'}) {
                   16689:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16690:         }
1.444     albertel 16691:     }
1.566     albertel 16692: 
1.444     albertel 16693: #
                   16694: # Set environment (will override cloned, if existing)
                   16695: #
                   16696:     my @sections = ();
                   16697:     my @xlists = ();
                   16698:     if ($args->{'crstype'}) {
                   16699:         $cenv{'type'}=$args->{'crstype'};
                   16700:     }
1.1371    raeburn  16701:     if ($args->{'lti'}) {
                   16702:         $cenv{'internal.lti'}=$args->{'lti'};
                   16703:     }
1.444     albertel 16704:     if ($args->{'crsid'}) {
                   16705:         $cenv{'courseid'}=$args->{'crsid'};
                   16706:     }
                   16707:     if ($args->{'crscode'}) {
                   16708:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16709:     }
                   16710:     if ($args->{'crsquota'} ne '') {
                   16711:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16712:     } else {
                   16713:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16714:     }
                   16715:     if ($args->{'ccuname'}) {
                   16716:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16717:                                         ':'.$args->{'ccdomain'};
                   16718:     } else {
                   16719:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16720:     }
1.1116    raeburn  16721:     if ($args->{'defaultcredits'}) {
                   16722:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16723:     }
1.444     albertel 16724:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16725:     if ($args->{'crssections'}) {
                   16726:         $cenv{'internal.sectionnums'} = '';
                   16727:         if ($args->{'crssections'} =~ m/,/) {
                   16728:             @sections = split/,/,$args->{'crssections'};
                   16729:         } else {
                   16730:             $sections[0] = $args->{'crssections'};
                   16731:         }
                   16732:         if (@sections > 0) {
                   16733:             foreach my $item (@sections) {
                   16734:                 my ($sec,$gp) = split/:/,$item;
                   16735:                 my $class = $args->{'crscode'}.$sec;
                   16736:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16737:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16738:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16739:                     push(@badclasses,$class);
1.444     albertel 16740:                 }
                   16741:             }
                   16742:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16743:         }
                   16744:     }
                   16745: # do not hide course coordinator from staff listing, 
                   16746: # even if privileged
                   16747:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16748: # add course coordinator's domain to domains to check for privileged users
                   16749: # if different to course domain
                   16750:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16751:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16752:     }
1.444     albertel 16753: # add crosslistings
                   16754:     if ($args->{'crsxlist'}) {
                   16755:         $cenv{'internal.crosslistings'}='';
                   16756:         if ($args->{'crsxlist'} =~ m/,/) {
                   16757:             @xlists = split/,/,$args->{'crsxlist'};
                   16758:         } else {
                   16759:             $xlists[0] = $args->{'crsxlist'};
                   16760:         }
                   16761:         if (@xlists > 0) {
                   16762:             foreach my $item (@xlists) {
                   16763:                 my ($xl,$gp) = split/:/,$item;
                   16764:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16765:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16766:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16767:                     push(@badclasses,$xl);
1.444     albertel 16768:                 }
                   16769:             }
                   16770:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16771:         }
                   16772:     }
                   16773:     if ($args->{'autoadds'}) {
                   16774:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16775:     }
                   16776:     if ($args->{'autodrops'}) {
                   16777:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16778:     }
                   16779: # check for notification of enrollment changes
                   16780:     my @notified = ();
                   16781:     if ($args->{'notify_owner'}) {
                   16782:         if ($args->{'ccuname'} ne '') {
                   16783:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16784:         }
                   16785:     }
                   16786:     if ($args->{'notify_dc'}) {
                   16787:         if ($uname ne '') { 
1.630     raeburn  16788:             push(@notified,$uname.':'.$udom);
1.444     albertel 16789:         }
                   16790:     }
                   16791:     if (@notified > 0) {
                   16792:         my $notifylist;
                   16793:         if (@notified > 1) {
                   16794:             $notifylist = join(',',@notified);
                   16795:         } else {
                   16796:             $notifylist = $notified[0];
                   16797:         }
                   16798:         $cenv{'internal.notifylist'} = $notifylist;
                   16799:     }
                   16800:     if (@badclasses > 0) {
                   16801:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16802:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16803:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16804:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16805:         );
1.1264    raeburn  16806:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16807:                            &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  16808:         if ($context eq 'auto') {
                   16809:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16810:         } else {
1.566     albertel 16811:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16812:         }
                   16813:         foreach my $item (@badclasses) {
1.541     raeburn  16814:             if ($context eq 'auto') {
1.1261    raeburn  16815:                 $outcome .= " - $item\n";
1.541     raeburn  16816:             } else {
1.1261    raeburn  16817:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16818:             }
1.1261    raeburn  16819:         }
                   16820:         if ($context eq 'auto') {
                   16821:             $outcome .= $linefeed;
                   16822:         } else {
                   16823:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16824:         } 
1.444     albertel 16825:     }
                   16826:     if ($args->{'no_end_date'}) {
                   16827:         $args->{'endaccess'} = 0;
                   16828:     }
                   16829:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16830:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16831:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16832:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16833:     if ($args->{'showphotos'}) {
                   16834:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16835:     }
                   16836:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16837:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16838:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16839:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16840:             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'); 
                   16841:             if ($context eq 'auto') {
                   16842:                 $outcome .= $krb_msg;
                   16843:             } else {
1.566     albertel 16844:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16845:             }
                   16846:             $outcome .= $linefeed;
1.444     albertel 16847:         }
                   16848:     }
                   16849:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16850:        if ($args->{'setpolicy'}) {
                   16851:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16852:        }
                   16853:        if ($args->{'setcontent'}) {
                   16854:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16855:        }
1.1251    raeburn  16856:        if ($args->{'setcomment'}) {
                   16857:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16858:        }
1.444     albertel 16859:     }
                   16860:     if ($args->{'reshome'}) {
                   16861: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16862: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16863:     }
                   16864: #
                   16865: # course has keyed access
                   16866: #
                   16867:     if ($args->{'setkeys'}) {
                   16868:        $cenv{'keyaccess'}='yes';
                   16869:     }
                   16870: # if specified, key authority is not course, but user
                   16871: # only active if keyaccess is yes
                   16872:     if ($args->{'keyauth'}) {
1.487     albertel 16873: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16874: 	$user = &LONCAPA::clean_username($user);
                   16875: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16876: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16877: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16878: 	}
                   16879:     }
                   16880: 
1.1166    raeburn  16881: #
1.1167    raeburn  16882: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16883: #
                   16884:     if ($args->{'uniquecode'}) {
                   16885:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16886:         if ($code) {
                   16887:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16888:             my %crsinfo =
                   16889:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16890:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16891:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16892:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16893:             } 
1.1166    raeburn  16894:             if (ref($coderef)) {
                   16895:                 $$coderef = $code;
                   16896:             }
                   16897:         }
                   16898:     }
                   16899: 
1.444     albertel 16900:     if ($args->{'disresdis'}) {
                   16901:         $cenv{'pch.roles.denied'}='st';
                   16902:     }
                   16903:     if ($args->{'disablechat'}) {
                   16904:         $cenv{'plc.roles.denied'}='st';
                   16905:     }
                   16906: 
                   16907:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16908:     # course
                   16909:     $cenv{'course.helper.not.run'} = 1;
                   16910:     #
                   16911:     # Use new Randomseed
                   16912:     #
                   16913:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16914:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16915:     #
                   16916:     # The encryption code and receipt prefix for this course
                   16917:     #
                   16918:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16919:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16920:     #
                   16921:     # By default, use standard grading
                   16922:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16923: 
1.541     raeburn  16924:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16925:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16926: #
                   16927: # Open all assignments
                   16928: #
                   16929:     if ($args->{'openall'}) {
1.1341    raeburn  16930:        my $opendate = time;
                   16931:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16932:            $opendate = $args->{'openallfrom'};
                   16933:        }
1.444     albertel 16934:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16935:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16936:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16937:        $outcome .= &mt('All assignments open starting [_1]',
                   16938:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16939:                    &Apache::lonnet::cput
                   16940:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16941:    }
                   16942: #
                   16943: # Set first page
                   16944: #
                   16945:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16946: 	    || ($cloneid)) {
1.445     albertel 16947: 	use LONCAPA::map;
1.444     albertel 16948: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16949: 
                   16950: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16951:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16952: 
1.444     albertel 16953:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16954:         my $title; my $url;
                   16955:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16956: 	    $title=&mt('Syllabus');
1.444     albertel 16957:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16958:         } else {
1.963     raeburn  16959:             $title=&mt('Table of Contents');
1.444     albertel 16960:             $url='/adm/navmaps';
                   16961:         }
1.445     albertel 16962: 
                   16963:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16964: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16965: 
                   16966: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16967:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16968:     }
1.566     albertel 16969: 
1.1237    raeburn  16970: # 
                   16971: # Set params for Placement Tests
                   16972: #
1.1239    raeburn  16973:     if ($args->{'crstype'} eq 'Placement') {
                   16974:        my %storecontent; 
                   16975:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16976:        my %defaults = (
                   16977:                         buttonshide   => { value => 'yes',
                   16978:                                            type => 'string_yesno',},
                   16979:                         type          => { value => 'randomizetry',
                   16980:                                            type  => 'string_questiontype',},
                   16981:                         maxtries      => { value => 1,
                   16982:                                            type => 'int_pos',},
                   16983:                         problemstatus => { value => 'no',
                   16984:                                            type  => 'string_problemstatus',},
                   16985:                       );
                   16986:        foreach my $key (keys(%defaults)) {
                   16987:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16988:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16989:        }
1.1237    raeburn  16990:        &Apache::lonnet::cput
                   16991:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16992:     }
                   16993: 
1.1344    raeburn  16994:     return (1,$outcome,\@clonemsg);
1.444     albertel 16995: }
                   16996: 
1.1166    raeburn  16997: sub make_unique_code {
                   16998:     my ($cdom,$cnum) = @_;
                   16999:     # get lock on uniquecodes db
                   17000:     my $lockhash = {
                   17001:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17002:                                                   ':'.$env{'user.domain'},
                   17003:                    };
                   17004:     my $tries = 0;
                   17005:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17006:     my ($code,$error);
                   17007:   
                   17008:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17009:         $tries ++;
                   17010:         sleep 1;
                   17011:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17012:     }
                   17013:     if ($gotlock eq 'ok') {
                   17014:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17015:         my $gotcode;
                   17016:         my $attempts = 0;
                   17017:         while ((!$gotcode) && ($attempts < 100)) {
                   17018:             $code = &generate_code();
                   17019:             if (!exists($currcodes{$code})) {
                   17020:                 $gotcode = 1;
                   17021:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17022:                     $error = 'nostore';
                   17023:                 }
                   17024:             }
                   17025:             $attempts ++;
                   17026:         }
                   17027:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17028:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17029:     } else {
                   17030:         $error = 'nolock';
                   17031:     }
                   17032:     return ($code,$error);
                   17033: }
                   17034: 
                   17035: sub generate_code {
                   17036:     my $code;
                   17037:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17038:     for (my $i=0; $i<6; $i++) {
                   17039:         my $lettnum = int (rand 2);
                   17040:         my $item = '';
                   17041:         if ($lettnum) {
                   17042:             $item = $letts[int( rand(18) )];
                   17043:         } else {
                   17044:             $item = 1+int( rand(8) );
                   17045:         }
                   17046:         $code .= $item;
                   17047:     }
                   17048:     return $code;
                   17049: }
                   17050: 
1.444     albertel 17051: ############################################################
                   17052: ############################################################
                   17053: 
1.1237    raeburn  17054: # Community, Course and Placement Test
1.378     raeburn  17055: sub course_type {
                   17056:     my ($cid) = @_;
                   17057:     if (!defined($cid)) {
                   17058:         $cid = $env{'request.course.id'};
                   17059:     }
1.404     albertel 17060:     if (defined($env{'course.'.$cid.'.type'})) {
                   17061:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17062:     } else {
                   17063:         return 'Course';
1.377     raeburn  17064:     }
                   17065: }
1.156     albertel 17066: 
1.406     raeburn  17067: sub group_term {
                   17068:     my $crstype = &course_type();
                   17069:     my %names = (
                   17070:                   'Course' => 'group',
1.865     raeburn  17071:                   'Community' => 'group',
1.1237    raeburn  17072:                   'Placement' => 'group',
1.406     raeburn  17073:                 );
                   17074:     return $names{$crstype};
                   17075: }
                   17076: 
1.902     raeburn  17077: sub course_types {
1.1310    raeburn  17078:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17079:     my %typename = (
                   17080:                          official   => 'Official course',
                   17081:                          unofficial => 'Unofficial course',
                   17082:                          community  => 'Community',
1.1165    raeburn  17083:                          textbook   => 'Textbook course',
1.1237    raeburn  17084:                          placement  => 'Placement test',
1.1310    raeburn  17085:                          lti        => 'LTI provider',
1.902     raeburn  17086:                    );
                   17087:     return (\@types,\%typename);
                   17088: }
                   17089: 
1.156     albertel 17090: sub icon {
                   17091:     my ($file)=@_;
1.505     albertel 17092:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17093:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17094:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17095:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17096: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17097: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17098: 	            $curfext.".gif") {
                   17099: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17100: 		$curfext.".gif";
                   17101: 	}
                   17102:     }
1.249     albertel 17103:     return &lonhttpdurl($iconname);
1.154     albertel 17104: } 
1.84      albertel 17105: 
1.575     albertel 17106: sub lonhttpdurl {
1.692     www      17107: #
                   17108: # Had been used for "small fry" static images on separate port 8080.
                   17109: # Modify here if lightweight http functionality desired again.
                   17110: # Currently eliminated due to increasing firewall issues.
                   17111: #
1.575     albertel 17112:     my ($url)=@_;
1.692     www      17113:     return $url;
1.215     albertel 17114: }
                   17115: 
1.213     albertel 17116: sub connection_aborted {
                   17117:     my ($r)=@_;
                   17118:     $r->print(" ");$r->rflush();
                   17119:     my $c = $r->connection;
                   17120:     return $c->aborted();
                   17121: }
                   17122: 
1.221     foxr     17123: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17124: #    strings as 'strings'.
                   17125: sub escape_single {
1.221     foxr     17126:     my ($input) = @_;
1.223     albertel 17127:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17128:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17129:     return $input;
                   17130: }
1.223     albertel 17131: 
1.222     foxr     17132: #  Same as escape_single, but escape's "'s  This 
                   17133: #  can be used for  "strings"
                   17134: sub escape_double {
                   17135:     my ($input) = @_;
                   17136:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17137:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17138:     return $input;
                   17139: }
1.223     albertel 17140:  
1.222     foxr     17141: #   Escapes the last element of a full URL.
                   17142: sub escape_url {
                   17143:     my ($url)   = @_;
1.238     raeburn  17144:     my @urlslices = split(/\//, $url,-1);
1.369     www      17145:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17146:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17147: }
1.462     albertel 17148: 
1.820     raeburn  17149: sub compare_arrays {
                   17150:     my ($arrayref1,$arrayref2) = @_;
                   17151:     my (@difference,%count);
                   17152:     @difference = ();
                   17153:     %count = ();
                   17154:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17155:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17156:         foreach my $element (keys(%count)) {
                   17157:             if ($count{$element} == 1) {
                   17158:                 push(@difference,$element);
                   17159:             }
                   17160:         }
                   17161:     }
                   17162:     return @difference;
                   17163: }
                   17164: 
1.1322    raeburn  17165: sub lon_status_items {
                   17166:     my %defaults = (
                   17167:                      E         => 100,
                   17168:                      W         => 4,
                   17169:                      N         => 1,
1.1324    raeburn  17170:                      U         => 5,
1.1322    raeburn  17171:                      threshold => 200,
                   17172:                      sysmail   => 2500,
                   17173:                    );
                   17174:     my %names = (
                   17175:                    E => 'Errors',
                   17176:                    W => 'Warnings',
                   17177:                    N => 'Notices',
1.1324    raeburn  17178:                    U => 'Unsent',
1.1322    raeburn  17179:                 );
                   17180:     return (\%defaults,\%names);
                   17181: }
                   17182: 
1.817     bisitz   17183: # -------------------------------------------------------- Initialize user login
1.462     albertel 17184: sub init_user_environment {
1.463     albertel 17185:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17186:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17187: 
                   17188:     my $public=($username eq 'public' && $domain eq 'public');
                   17189: 
1.1062    raeburn  17190:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17191:     my $now=time;
                   17192: 
                   17193:     if ($public) {
                   17194: 	my $max_public=100;
                   17195: 	my $oldest;
                   17196: 	my $oldest_time=0;
                   17197: 	for(my $next=1;$next<=$max_public;$next++) {
                   17198: 	    if (-e $lonids."/publicuser_$next.id") {
                   17199: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17200: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17201: 		    $oldest_time=$mtime;
                   17202: 		    $oldest=$next;
                   17203: 		}
                   17204: 	    } else {
                   17205: 		$cookie="publicuser_$next";
                   17206: 		last;
                   17207: 	    }
                   17208: 	}
                   17209: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17210:     } else {
1.1275    raeburn  17211: 	# See if old ID present, if so, remove if this isn't a robot,
                   17212: 	# killing any existing non-robot sessions
1.463     albertel 17213: 	if (!$args->{'robot'}) {
                   17214: 	    opendir(DIR,$lonids);
                   17215: 	    while ($filename=readdir(DIR)) {
                   17216: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17217:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17218:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17219:                         my $linkedfile;
1.1320    raeburn  17220:                         if (exists($oldenv{'user.linkedenv'})) {
                   17221:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17222:                         }
1.1320    raeburn  17223:                         untie(%oldenv);
                   17224:                         if (unlink("$lonids/$filename")) {
                   17225:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17226:                                 if (-l "$lonids/$linkedfile.id") {
                   17227:                                     unlink("$lonids/$linkedfile.id");
                   17228:                                 }
1.1295    raeburn  17229:                             }
                   17230:                         }
                   17231:                     } else {
                   17232:                         unlink($lonids.'/'.$filename);
                   17233:                     }
1.463     albertel 17234: 		}
1.462     albertel 17235: 	    }
1.463     albertel 17236: 	    closedir(DIR);
1.1204    raeburn  17237: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17238:             my $namespace = 'nohist_courseeditor';
                   17239:             my $lockingkey = 'paste'."\0".'locked_num';
                   17240:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17241:                                                 $domain,$username);
                   17242:             if (exists($lockhash{$lockingkey})) {
                   17243:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17244:                 unless ($delresult eq 'ok') {
                   17245:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17246:                 }
                   17247:             }
1.462     albertel 17248: 	}
                   17249: # Give them a new cookie
1.463     albertel 17250: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17251: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17252: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17253:     
                   17254: # Initialize roles
                   17255: 
1.1062    raeburn  17256: 	($userroles,$firstaccenv,$timerintenv) = 
                   17257:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17258:     }
                   17259: # ------------------------------------ Check browser type and MathML capability
                   17260: 
1.1194    raeburn  17261:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17262:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17263: 
                   17264: # ------------------------------------------------------------- Get environment
                   17265: 
                   17266:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17267:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17268:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17269: 	undef(%userenv);
                   17270:     }
                   17271:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17272: 	$form->{'interface'}=$userenv{'interface'};
                   17273:     }
                   17274:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17275: 
                   17276: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17277:     foreach my $option ('interface','localpath','localres') {
                   17278:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17279:     }
                   17280: # --------------------------------------------------------- Write first profile
                   17281: 
                   17282:     {
1.1350    raeburn  17283:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17284: 	my %initial_env = 
                   17285: 	    ("user.name"          => $username,
                   17286: 	     "user.domain"        => $domain,
                   17287: 	     "user.home"          => $authhost,
                   17288: 	     "browser.type"       => $clientbrowser,
                   17289: 	     "browser.version"    => $clientversion,
                   17290: 	     "browser.mathml"     => $clientmathml,
                   17291: 	     "browser.unicode"    => $clientunicode,
                   17292: 	     "browser.os"         => $clientos,
1.1137    raeburn  17293:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17294:              "browser.info"       => $clientinfo,
1.1194    raeburn  17295:              "browser.osversion"  => $clientosversion,
1.462     albertel 17296: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17297: 	     "request.course.fn"  => '',
                   17298: 	     "request.course.uri" => '',
                   17299: 	     "request.course.sec" => '',
                   17300: 	     "request.role"       => 'cm',
                   17301: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17302: 	     "request.host"       => $ip,);
1.462     albertel 17303: 
                   17304:         if ($form->{'localpath'}) {
                   17305: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17306: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17307:         }
                   17308: 	
                   17309: 	if ($form->{'interface'}) {
                   17310: 	    $form->{'interface'}=~s/\W//gs;
                   17311: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17312: 	    $env{'browser.interface'}=$form->{'interface'};
                   17313: 	}
                   17314: 
1.1157    raeburn  17315:         if ($form->{'iptoken'}) {
                   17316:             my $lonhost = $r->dir_config('lonHostID');
                   17317:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17318:             $env{'user.noloadbalance'} = $lonhost;
                   17319:         }
                   17320: 
1.1268    raeburn  17321:         if ($form->{'noloadbalance'}) {
                   17322:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17323:             my $hosthere = $form->{'noloadbalance'};
                   17324:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17325:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17326:                 $env{'user.noloadbalance'} = $hosthere;
                   17327:             }
                   17328:         }
                   17329: 
1.1016    raeburn  17330:         unless ($domain eq 'public') {
1.1273    raeburn  17331:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17332:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17333: 
                   17334:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   17335:                 $userenv{'availabletools.'.$tool} = 
                   17336:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17337:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17338:             }
1.980     raeburn  17339: 
1.1311    raeburn  17340:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17341:                 $userenv{'canrequest.'.$crstype} =
                   17342:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17343:                                                       'reload','requestcourses',
                   17344:                                                       \%userenv,\%domdef,\%is_adv);
                   17345:             }
1.724     raeburn  17346: 
1.1273    raeburn  17347:             $userenv{'canrequest.author'} =
                   17348:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17349:                                                   'reload','requestauthor',
1.980     raeburn  17350:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17351:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17352:                                                  $domain,$username);
                   17353:             my $reqstatus = $reqauthor{'author_status'};
                   17354:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17355:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17356:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17357:                                                       $reqauthor{'author'}{'timestamp'};
                   17358:                 }
1.1092    raeburn  17359:             }
1.1287    raeburn  17360:             my ($types,$typename) = &course_types();
                   17361:             if (ref($types) eq 'ARRAY') {
                   17362:                 my @options = ('approval','validate','autolimit');
                   17363:                 my $optregex = join('|',@options);
                   17364:                 my (%willtrust,%trustchecked);
                   17365:                 foreach my $type (@{$types}) {
                   17366:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17367:                     if ($dom_str ne '') {
                   17368:                         my $updatedstr = '';
                   17369:                         my @possdomains = split(',',$dom_str);
                   17370:                         foreach my $entry (@possdomains) {
                   17371:                             my ($extdom,$extopt) = split(':',$entry);
                   17372:                             unless ($trustchecked{$extdom}) {
                   17373:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17374:                                 $trustchecked{$extdom} = 1;
                   17375:                             }
                   17376:                             if ($willtrust{$extdom}) {
                   17377:                                 $updatedstr .= $entry.',';
                   17378:                             }
                   17379:                         }
                   17380:                         $updatedstr =~ s/,$//;
                   17381:                         if ($updatedstr) {
                   17382:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17383:                         } else {
                   17384:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17385:                         }
                   17386:                     }
                   17387:                 }
                   17388:             }
1.1092    raeburn  17389:         }
1.462     albertel 17390: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17391: 
1.462     albertel 17392: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17393: 		 &GDBM_WRCREAT(),0640)) {
                   17394: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17395: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17396: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17397:             if (ref($firstaccenv) eq 'HASH') {
                   17398:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17399:             }
                   17400:             if (ref($timerintenv) eq 'HASH') {
                   17401:                 &_add_to_env(\%disk_env,$timerintenv);
                   17402:             }
1.463     albertel 17403: 	    if (ref($args->{'extra_env'})) {
                   17404: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17405: 	    }
1.462     albertel 17406: 	    untie(%disk_env);
                   17407: 	} else {
1.705     tempelho 17408: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17409: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17410: 	    return 'error: '.$!;
                   17411: 	}
                   17412:     }
                   17413:     $env{'request.role'}='cm';
                   17414:     $env{'request.role.adv'}=$env{'user.adv'};
                   17415:     $env{'browser.type'}=$clientbrowser;
                   17416: 
                   17417:     return $cookie;
                   17418: 
                   17419: }
                   17420: 
                   17421: sub _add_to_env {
                   17422:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17423:     if (ref($env_data) eq 'HASH') {
                   17424:         while (my ($key,$value) = each(%$env_data)) {
                   17425: 	    $idf->{$prefix.$key} = $value;
                   17426: 	    $env{$prefix.$key}   = $value;
                   17427:         }
1.462     albertel 17428:     }
                   17429: }
                   17430: 
1.685     tempelho 17431: # --- Get the symbolic name of a problem and the url
                   17432: sub get_symb {
                   17433:     my ($request,$silent) = @_;
1.726     raeburn  17434:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17435:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17436:     if ($symb eq '') {
                   17437:         if (!$silent) {
1.1071    raeburn  17438:             if (ref($request)) { 
                   17439:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17440:             }
1.685     tempelho 17441:             return ();
                   17442:         }
                   17443:     }
                   17444:     &Apache::lonenc::check_decrypt(\$symb);
                   17445:     return ($symb);
                   17446: }
                   17447: 
                   17448: # --------------------------------------------------------------Get annotation
                   17449: 
                   17450: sub get_annotation {
                   17451:     my ($symb,$enc) = @_;
                   17452: 
                   17453:     my $key = $symb;
                   17454:     if (!$enc) {
                   17455:         $key =
                   17456:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17457:     }
                   17458:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17459:     return $annotation{$key};
                   17460: }
                   17461: 
                   17462: sub clean_symb {
1.731     raeburn  17463:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17464: 
                   17465:     &Apache::lonenc::check_decrypt(\$symb);
                   17466:     my $enc = $env{'request.enc'};
1.731     raeburn  17467:     if ($delete_enc) {
1.730     raeburn  17468:         delete($env{'request.enc'});
                   17469:     }
1.685     tempelho 17470: 
                   17471:     return ($symb,$enc);
                   17472: }
1.462     albertel 17473: 
1.1181    raeburn  17474: ############################################################
                   17475: ############################################################
                   17476: 
                   17477: =pod
                   17478: 
                   17479: =head1 Routines for building display used to search for courses
                   17480: 
                   17481: 
                   17482: =over 4
                   17483: 
                   17484: =item * &build_filters()
                   17485: 
                   17486: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17487: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17488: and quotacheck.pl
                   17489: 
1.1181    raeburn  17490: 
                   17491: Inputs:
                   17492: 
                   17493: filterlist - anonymous array of fields to include as potential filters 
                   17494: 
                   17495: crstype - course type
                   17496: 
                   17497: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17498:               to pop-open a course selector (will contain "extra element"). 
                   17499: 
                   17500: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17501: 
                   17502: filter - anonymous hash of criteria and their values
                   17503: 
                   17504: action - form action
                   17505: 
                   17506: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17507: 
1.1182    raeburn  17508: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17509: 
                   17510: cloneruname - username of owner of new course who wants to clone
                   17511: 
                   17512: clonerudom - domain of owner of new course who wants to clone
                   17513: 
                   17514: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17515: 
                   17516: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17517: 
                   17518: codedom - domain
                   17519: 
                   17520: formname - value of form element named "form". 
                   17521: 
                   17522: fixeddom - domain, if fixed.
                   17523: 
                   17524: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17525: 
                   17526: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17527: 
                   17528: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17529: 
                   17530: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17531: 
                   17532: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17533: 
                   17534: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17535: 
                   17536: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17537: 
1.1182    raeburn  17538: 
1.1181    raeburn  17539: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17540: 
1.1182    raeburn  17541: 
1.1181    raeburn  17542: Side Effects: None
                   17543: 
                   17544: =cut
                   17545: 
                   17546: # ---------------------------------------------- search for courses based on last activity etc.
                   17547: 
                   17548: sub build_filters {
                   17549:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17550:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17551:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17552:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17553:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17554:     my ($list,$jscript);
1.1181    raeburn  17555:     my $onchange = 'javascript:updateFilters(this)';
                   17556:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17557:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17558:         $typeselectform,$instcodetitle);
                   17559:     if ($formname eq '') {
                   17560:         $formname = $caller;
                   17561:     }
                   17562:     foreach my $item (@{$filterlist}) {
                   17563:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17564:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17565:             if ($item eq 'domainfilter') {
                   17566:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17567:             } elsif ($item eq 'coursefilter') {
                   17568:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17569:             } elsif ($item eq 'ownerfilter') {
                   17570:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17571:             } elsif ($item eq 'ownerdomfilter') {
                   17572:                 $filter->{'ownerdomfilter'} =
                   17573:                     &LONCAPA::clean_domain($filter->{$item});
                   17574:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17575:                                                        'ownerdomfilter',1);
                   17576:             } elsif ($item eq 'personfilter') {
                   17577:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17578:             } elsif ($item eq 'persondomfilter') {
                   17579:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17580:                                                         'persondomfilter',1);
                   17581:             } else {
                   17582:                 $filter->{$item} =~ s/\W//g;
                   17583:             }
                   17584:             if (!$filter->{$item}) {
                   17585:                 $filter->{$item} = '';
                   17586:             }
                   17587:         }
                   17588:         if ($item eq 'domainfilter') {
                   17589:             my $allow_blank = 1;
                   17590:             if ($formname eq 'portform') {
                   17591:                 $allow_blank=0;
                   17592:             } elsif ($formname eq 'studentform') {
                   17593:                 $allow_blank=0;
                   17594:             }
                   17595:             if ($fixeddom) {
                   17596:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17597:                                     ' value="'.$codedom.'" />'.
                   17598:                                     &Apache::lonnet::domain($codedom,'description');
                   17599:             } else {
                   17600:                 $domainselectform = &select_dom_form($filter->{$item},
                   17601:                                                      'domainfilter',
                   17602:                                                       $allow_blank,'',$onchange);
                   17603:             }
                   17604:         } else {
                   17605:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17606:         }
                   17607:     }
                   17608: 
                   17609:     # last course activity filter and selection
                   17610:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17611: 
                   17612:     # course created filter and selection
                   17613:     if (exists($filter->{'createdfilter'})) {
                   17614:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17615:     }
                   17616: 
1.1239    raeburn  17617:     my $prefix = $crstype;
                   17618:     if ($crstype eq 'Placement') {
                   17619:         $prefix = 'Placement Test'
                   17620:     }
1.1181    raeburn  17621:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17622:                 'cac' => "$prefix Activity",
                   17623:                 'ccr' => "$prefix Created",
                   17624:                 'cde' => "$prefix Title",
                   17625:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17626:                 'ins' => 'Institutional Code',
                   17627:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17628:                 'cow' => "$prefix Owner/Co-owner",
                   17629:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17630:                 'cog' => 'Type',
                   17631:              );
                   17632: 
                   17633:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17634:         my $typeval = 'Course';
                   17635:         if ($crstype eq 'Community') {
                   17636:             $typeval = 'Community';
1.1239    raeburn  17637:         } elsif ($crstype eq 'Placement') {
                   17638:             $typeval = 'Placement';
1.1181    raeburn  17639:         }
                   17640:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17641:     } else {
                   17642:         $typeselectform =  '<select name="type" size="1"';
                   17643:         if ($onchange) {
                   17644:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17645:         }
                   17646:         $typeselectform .= '>'."\n";
1.1237    raeburn  17647:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17648:             my $shown;
                   17649:             if ($posstype eq 'Placement') {
                   17650:                 $shown = &mt('Placement Test');
                   17651:             } else {
                   17652:                 $shown = &mt($posstype);
                   17653:             }
1.1181    raeburn  17654:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17655:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17656:         }
                   17657:         $typeselectform.="</select>";
                   17658:     }
                   17659: 
                   17660:     my ($cloneableonlyform,$cloneabletitle);
                   17661:     if (exists($filter->{'cloneableonly'})) {
                   17662:         my $cloneableon = '';
                   17663:         my $cloneableoff = ' checked="checked"';
                   17664:         if ($filter->{'cloneableonly'}) {
                   17665:             $cloneableon = $cloneableoff;
                   17666:             $cloneableoff = '';
                   17667:         }
                   17668:         $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>';
                   17669:         if ($formname eq 'ccrs') {
1.1187    bisitz   17670:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17671:         } else {
                   17672:             $cloneabletitle = &mt('Cloneable by you');
                   17673:         }
                   17674:     }
                   17675:     my $officialjs;
                   17676:     if ($crstype eq 'Course') {
                   17677:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17678: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17679: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17680:             if ($codedom) { 
1.1181    raeburn  17681:                 $officialjs = 1;
                   17682:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17683:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17684:                                                                   $officialjs,$codetitlesref);
                   17685:                 if ($jscript) {
1.1182    raeburn  17686:                     $jscript = '<script type="text/javascript">'."\n".
                   17687:                                '// <![CDATA['."\n".
                   17688:                                $jscript."\n".
                   17689:                                '// ]]>'."\n".
                   17690:                                '</script>'."\n";
1.1181    raeburn  17691:                 }
                   17692:             }
                   17693:             if ($instcodeform eq '') {
                   17694:                 $instcodeform =
                   17695:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17696:                     $list->{'instcodefilter'}.'" />';
                   17697:                 $instcodetitle = $lt{'ins'};
                   17698:             } else {
                   17699:                 $instcodetitle = $lt{'inc'};
                   17700:             }
                   17701:             if ($fixeddom) {
                   17702:                 $instcodetitle .= '<br />('.$codedom.')';
                   17703:             }
                   17704:         }
                   17705:     }
                   17706:     my $output = qq|
                   17707: <form method="post" name="filterpicker" action="$action">
                   17708: <input type="hidden" name="form" value="$formname" />
                   17709: |;
                   17710:     if ($formname eq 'modifycourse') {
                   17711:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17712:                    '<input type="hidden" name="prevphase" value="'.
                   17713:                    $prevphase.'" />'."\n";
1.1198    musolffc 17714:     } elsif ($formname eq 'quotacheck') {
                   17715:         $output .= qq|
                   17716: <input type="hidden" name="sortby" value="" />
                   17717: <input type="hidden" name="sortorder" value="" />
                   17718: |;
                   17719:     } else {
1.1181    raeburn  17720:         my $name_input;
                   17721:         if ($cnameelement ne '') {
                   17722:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17723:                           $cnameelement.'" />';
                   17724:         }
                   17725:         $output .= qq|
1.1182    raeburn  17726: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17727: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17728: $name_input
                   17729: $roleelement
                   17730: $multelement
                   17731: $typeelement
                   17732: |;
                   17733:         if ($formname eq 'portform') {
                   17734:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17735:         }
                   17736:     }
                   17737:     if ($fixeddom) {
                   17738:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17739:     }
                   17740:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17741:     if ($sincefilterform) {
                   17742:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17743:                   .$sincefilterform
                   17744:                   .&Apache::lonhtmlcommon::row_closure();
                   17745:     }
                   17746:     if ($createdfilterform) {
                   17747:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17748:                   .$createdfilterform
                   17749:                   .&Apache::lonhtmlcommon::row_closure();
                   17750:     }
                   17751:     if ($domainselectform) {
                   17752:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17753:                   .$domainselectform
                   17754:                   .&Apache::lonhtmlcommon::row_closure();
                   17755:     }
                   17756:     if ($typeselectform) {
                   17757:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17758:             $output .= $typeselectform;
                   17759:         } else {
                   17760:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17761:                       .$typeselectform
                   17762:                       .&Apache::lonhtmlcommon::row_closure();
                   17763:         }
                   17764:     }
                   17765:     if ($instcodeform) {
                   17766:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17767:                   .$instcodeform
                   17768:                   .&Apache::lonhtmlcommon::row_closure();
                   17769:     }
                   17770:     if (exists($filter->{'ownerfilter'})) {
                   17771:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17772:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17773:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17774:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17775:                    $ownerdomselectform.'</td></tr></table>'.
                   17776:                    &Apache::lonhtmlcommon::row_closure();
                   17777:     }
                   17778:     if (exists($filter->{'personfilter'})) {
                   17779:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17780:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17781:                    '<input type="text" name="personfilter" size="20" value="'.
                   17782:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17783:                    $persondomselectform.'</td></tr></table>'.
                   17784:                    &Apache::lonhtmlcommon::row_closure();
                   17785:     }
                   17786:     if (exists($filter->{'coursefilter'})) {
                   17787:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17788:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17789:                   .$list->{'coursefilter'}.'" />'
                   17790:                   .&Apache::lonhtmlcommon::row_closure();
                   17791:     }
                   17792:     if ($cloneableonlyform) {
                   17793:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17794:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17795:     }
                   17796:     if (exists($filter->{'descriptfilter'})) {
                   17797:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17798:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17799:                   .$list->{'descriptfilter'}.'" />'
                   17800:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17801:     }
                   17802:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17803:                '<input type="hidden" name="updater" value="" />'."\n".
                   17804:                '<input type="submit" name="gosearch" value="'.
                   17805:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17806:     return $jscript.$clonewarning.$output;
                   17807: }
                   17808: 
                   17809: =pod 
                   17810: 
                   17811: =item * &timebased_select_form()
                   17812: 
1.1182    raeburn  17813: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17814: filter e.g., Course Activity, Course Created, when searching for courses
                   17815: or communities
                   17816: 
                   17817: Inputs:
                   17818: 
                   17819: item - name of form element (sincefilter or createdfilter)
                   17820: 
                   17821: filter - anonymous hash of criteria and their values
                   17822: 
                   17823: Returns: HTML for a select box contained a blank, then six time selections,
                   17824:          with value set in incoming form variables currently selected. 
                   17825: 
                   17826: Side Effects: None
                   17827: 
                   17828: =cut
                   17829: 
                   17830: sub timebased_select_form {
                   17831:     my ($item,$filter) = @_;
                   17832:     if (ref($filter) eq 'HASH') {
                   17833:         $filter->{$item} =~ s/[^\d-]//g;
                   17834:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17835:         return &select_form(
                   17836:                             $filter->{$item},
                   17837:                             $item,
                   17838:                             {      '-1' => '',
                   17839:                                 '86400' => &mt('today'),
                   17840:                                '604800' => &mt('last week'),
                   17841:                               '2592000' => &mt('last month'),
                   17842:                               '7776000' => &mt('last three months'),
                   17843:                              '15552000' => &mt('last six months'),
                   17844:                              '31104000' => &mt('last year'),
                   17845:                     'select_form_order' =>
                   17846:                            ['-1','86400','604800','2592000','7776000',
                   17847:                             '15552000','31104000']});
                   17848:     }
                   17849: }
                   17850: 
                   17851: =pod
                   17852: 
                   17853: =item * &js_changer()
                   17854: 
                   17855: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17856: when course type or domain is changed, and also to hide 'Searching ...' on
                   17857: page load completion for page showing search result.
1.1181    raeburn  17858: 
                   17859: Inputs: None
                   17860: 
1.1183    raeburn  17861: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17862: 
                   17863: Side Effects: None
                   17864: 
                   17865: =cut
                   17866: 
                   17867: sub js_changer {
                   17868:     return <<ENDJS;
                   17869: <script type="text/javascript">
                   17870: // <![CDATA[
                   17871: function updateFilters(caller) {
                   17872:     if (typeof(caller) != "undefined") {
                   17873:         document.filterpicker.updater.value = caller.name;
                   17874:     }
                   17875:     document.filterpicker.submit();
                   17876: }
1.1183    raeburn  17877: 
                   17878: function hideSearching() {
                   17879:     if (document.getElementById('searching')) {
                   17880:         document.getElementById('searching').style.display = 'none';
                   17881:     }
                   17882:     return;
                   17883: }
                   17884: 
1.1181    raeburn  17885: // ]]>
                   17886: </script>
                   17887: 
                   17888: ENDJS
                   17889: }
                   17890: 
                   17891: =pod
                   17892: 
1.1182    raeburn  17893: =item * &search_courses()
                   17894: 
                   17895: Process selected filters form course search form and pass to lonnet::courseiddump
                   17896: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17897: 
                   17898: Inputs:
                   17899: 
                   17900: dom - domain being searched 
                   17901: 
                   17902: type - course type ('Course' or 'Community' or '.' if any).
                   17903: 
                   17904: filter - anonymous hash of criteria and their values
                   17905: 
                   17906: numtitles - for institutional codes - number of categories
                   17907: 
                   17908: cloneruname - optional username of new course owner
                   17909: 
                   17910: clonerudom - optional domain of new course owner
                   17911: 
1.1221    raeburn  17912: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17913:             (used when DC is using course creation form)
                   17914: 
                   17915: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17916: 
1.1221    raeburn  17917: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17918:            (and so can clone automatically)
                   17919: 
                   17920: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17921: 
                   17922: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17923:               courses to clone 
1.1182    raeburn  17924: 
                   17925: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17926: 
                   17927: 
                   17928: Side Effects: None
                   17929: 
                   17930: =cut
                   17931: 
                   17932: 
                   17933: sub search_courses {
1.1221    raeburn  17934:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17935:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17936:     my (%courses,%showcourses,$cloner);
                   17937:     if (($filter->{'ownerfilter'} ne '') ||
                   17938:         ($filter->{'ownerdomfilter'} ne '')) {
                   17939:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17940:                                        $filter->{'ownerdomfilter'};
                   17941:     }
                   17942:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17943:         if (!$filter->{$item}) {
                   17944:             $filter->{$item}='.';
                   17945:         }
                   17946:     }
                   17947:     my $now = time;
                   17948:     my $timefilter =
                   17949:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17950:     my ($createdbefore,$createdafter);
                   17951:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17952:         $createdbefore = $now;
                   17953:         $createdafter = $now-$filter->{'createdfilter'};
                   17954:     }
                   17955:     my ($instcodefilter,$regexpok);
                   17956:     if ($numtitles) {
                   17957:         if ($env{'form.official'} eq 'on') {
                   17958:             $instcodefilter =
                   17959:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17960:             $regexpok = 1;
                   17961:         } elsif ($env{'form.official'} eq 'off') {
                   17962:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17963:             unless ($instcodefilter eq '') {
                   17964:                 $regexpok = -1;
                   17965:             }
                   17966:         }
                   17967:     } else {
                   17968:         $instcodefilter = $filter->{'instcodefilter'};
                   17969:     }
                   17970:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17971:     if ($type eq '') { $type = '.'; }
                   17972: 
                   17973:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17974:         $cloner = $cloneruname.':'.$clonerudom;
                   17975:     }
                   17976:     %courses = &Apache::lonnet::courseiddump($dom,
                   17977:                                              $filter->{'descriptfilter'},
                   17978:                                              $timefilter,
                   17979:                                              $instcodefilter,
                   17980:                                              $filter->{'combownerfilter'},
                   17981:                                              $filter->{'coursefilter'},
                   17982:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17983:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17984:                                              $filter->{'cloneableonly'},
                   17985:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17986:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17987:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17988:         my $ccrole;
                   17989:         if ($type eq 'Community') {
                   17990:             $ccrole = 'co';
                   17991:         } else {
                   17992:             $ccrole = 'cc';
                   17993:         }
                   17994:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17995:                                                      $filter->{'persondomfilter'},
                   17996:                                                      'userroles',undef,
                   17997:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17998:                                                      $dom);
                   17999:         foreach my $role (keys(%rolehash)) {
                   18000:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18001:             my $cid = $cdom.'_'.$cnum;
                   18002:             if (exists($courses{$cid})) {
                   18003:                 if (ref($courses{$cid}) eq 'HASH') {
                   18004:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18005:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18006:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18007:                         }
                   18008:                     } else {
                   18009:                         $courses{$cid}{roles} = [$courserole];
                   18010:                     }
                   18011:                     $showcourses{$cid} = $courses{$cid};
                   18012:                 }
                   18013:             }
                   18014:         }
                   18015:         %courses = %showcourses;
                   18016:     }
                   18017:     return %courses;
                   18018: }
                   18019: 
                   18020: =pod
                   18021: 
1.1181    raeburn  18022: =back
                   18023: 
1.1207    raeburn  18024: =head1 Routines for version requirements for current course.
                   18025: 
                   18026: =over 4
                   18027: 
                   18028: =item * &check_release_required()
                   18029: 
                   18030: Compares required LON-CAPA version with version on server, and
                   18031: if required version is newer looks for a server with the required version.
                   18032: 
                   18033: Looks first at servers in user's owen domain; if none suitable, looks at
                   18034: servers in course's domain are permitted to host sessions for user's domain.
                   18035: 
                   18036: Inputs:
                   18037: 
                   18038: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18039: 
                   18040: $courseid - Course ID of current course
                   18041: 
                   18042: $rolecode - User's current role in course (for switchserver query string).
                   18043: 
                   18044: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18045: 
                   18046: 
                   18047: Returns:
                   18048: 
                   18049: $switchserver - query string tp append to /adm/switchserver call (if 
                   18050:                 current server's LON-CAPA version is too old. 
                   18051: 
                   18052: $warning - Message is displayed if no suitable server could be found.
                   18053: 
                   18054: =cut
                   18055: 
                   18056: sub check_release_required {
                   18057:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18058:     my ($switchserver,$warning);
                   18059:     if ($required ne '') {
                   18060:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18061:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18062:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18063:             my $otherserver;
                   18064:             if (($major eq '' && $minor eq '') ||
                   18065:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18066:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18067:                 my $switchlcrev =
                   18068:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18069:                                                            $userdomserver);
                   18070:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18071:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18072:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18073:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18074:                     if ($cdom ne $env{'user.domain'}) {
                   18075:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18076:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18077:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18078:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18079:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18080:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18081:                         my $canhost =
                   18082:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18083:                                                               $coursedomserver,
                   18084:                                                               $remoterev,
                   18085:                                                               $udomdefaults{'remotesessions'},
                   18086:                                                               $defdomdefaults{'hostedsessions'});
                   18087: 
                   18088:                         if ($canhost) {
                   18089:                             $otherserver = $coursedomserver;
                   18090:                         } else {
                   18091:                             $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.");
                   18092:                         }
                   18093:                     } else {
                   18094:                         $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).");
                   18095:                     }
                   18096:                 } else {
                   18097:                     $otherserver = $userdomserver;
                   18098:                 }
                   18099:             }
                   18100:             if ($otherserver ne '') {
                   18101:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18102:             }
                   18103:         }
                   18104:     }
                   18105:     return ($switchserver,$warning);
                   18106: }
                   18107: 
                   18108: =pod
                   18109: 
                   18110: =item * &check_release_result()
                   18111: 
                   18112: Inputs:
                   18113: 
                   18114: $switchwarning - Warning message if no suitable server found to host session.
                   18115: 
                   18116: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18117:                 and current role.
                   18118: 
                   18119: Returns: HTML to display with information about requirement to switch server.
                   18120:          Either displaying warning with link to Roles/Courses screen or
                   18121:          display link to switchserver.
                   18122: 
1.1181    raeburn  18123: =cut
                   18124: 
1.1207    raeburn  18125: sub check_release_result {
                   18126:     my ($switchwarning,$switchserver) = @_;
                   18127:     my $output = &start_page('Selected course unavailable on this server').
                   18128:                  '<p class="LC_warning">';
                   18129:     if ($switchwarning) {
                   18130:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18131:         if (&show_course()) {
                   18132:             $output .= &mt('Display courses');
                   18133:         } else {
                   18134:             $output .= &mt('Display roles');
                   18135:         }
                   18136:         $output .= '</a>';
                   18137:     } elsif ($switchserver) {
                   18138:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18139:                    '<br />'.
                   18140:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18141:                    &mt('Switch Server').
                   18142:                    '</a>';
                   18143:     }
                   18144:     $output .= '</p>'.&end_page();
                   18145:     return $output;
                   18146: }
                   18147: 
                   18148: =pod
                   18149: 
                   18150: =item * &needs_coursereinit()
                   18151: 
                   18152: Determine if course contents stored for user's session needs to be
                   18153: refreshed, because content has changed since "Big Hash" last tied.
                   18154: 
                   18155: Check for change is made if time last checked is more than 10 minutes ago
                   18156: (by default).
                   18157: 
                   18158: Inputs:
                   18159: 
                   18160: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18161: 
                   18162: $interval (optional) - Time which may elapse (in s) between last check for content
                   18163:                        change in current course. (default: 600 s).  
                   18164: 
                   18165: Returns: an array; first element is:
                   18166: 
                   18167: =over 4
                   18168: 
                   18169: 'switch' - if content updates mean user's session
                   18170:            needs to be switched to a server running a newer LON-CAPA version
                   18171:  
                   18172: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18173:            on current server hosting user's session                
                   18174: 
                   18175: ''       - if no action required.
                   18176: 
                   18177: =back
                   18178: 
                   18179: If first item element is 'switch':
                   18180: 
                   18181: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18182: 
                   18183: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18184:                               and current role. 
                   18185: 
                   18186: otherwise: no other elements returned.
                   18187: 
                   18188: =back
                   18189: 
                   18190: =cut
                   18191: 
                   18192: sub needs_coursereinit {
                   18193:     my ($loncaparev,$interval) = @_;
                   18194:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18195:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18196:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18197:     my $now = time;
                   18198:     if ($interval eq '') {
                   18199:         $interval = 600;
                   18200:     }
                   18201:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18202:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18203:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18204:         if ($blocked) {
                   18205:             return ();
                   18206:         }
1.1207    raeburn  18207:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18208:         if ($lastchange > $env{'request.course.tied'}) {
                   18209:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18210:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18211:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18212:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18213:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18214:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   18215:                     my ($switchserver,$switchwarning) =
                   18216:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18217:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   18218:                     if ($switchwarning ne '' || $switchserver ne '') {
                   18219:                         return ('switch',$switchwarning,$switchserver);
                   18220:                     }
                   18221:                 }
                   18222:             }
                   18223:             return ('update');
                   18224:         }
                   18225:     }
                   18226:     return ();
                   18227: }
1.1181    raeburn  18228: 
1.1083    raeburn  18229: sub update_content_constraints {
1.1326    raeburn  18230:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  18231:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18232:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18233:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18234:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18235:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18236:         if ($item eq 'resourcetag') {
                   18237:             if ($name eq 'responsetype') {
                   18238:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18239:             }
1.1307    raeburn  18240:         } elsif ($item eq 'course') {
                   18241:             if ($name eq 'courserestype') {
                   18242:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18243:             }
1.1083    raeburn  18244:         }
                   18245:     }
                   18246:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18247:     if (defined($navmap)) {
1.1307    raeburn  18248:         my (%allresponses,%allcrsrestypes);
                   18249:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18250:             if ($res->is_tool()) {
                   18251:                 if ($allcrsrestypes{'exttool'}) {
                   18252:                     $allcrsrestypes{'exttool'} ++;
                   18253:                 } else {
                   18254:                     $allcrsrestypes{'exttool'} = 1;
                   18255:                 }
                   18256:                 next;
                   18257:             }
1.1083    raeburn  18258:             my %responses = $res->responseTypes();
                   18259:             foreach my $key (keys(%responses)) {
                   18260:                 next unless(exists($checkresponsetypes{$key}));
                   18261:                 $allresponses{$key} += $responses{$key};
                   18262:             }
                   18263:         }
                   18264:         foreach my $key (keys(%allresponses)) {
                   18265:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18266:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18267:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18268:             }
                   18269:         }
1.1307    raeburn  18270:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18271:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18272:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18273:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18274:             }
                   18275:         }
1.1083    raeburn  18276:         undef($navmap);
                   18277:     }
1.1326    raeburn  18278:     my (@resources,@order,@resparms,@zombies);
                   18279:     if ($keeporder) {
                   18280:         use LONCAPA::map;
                   18281:         @resources = @LONCAPA::map::resources;
                   18282:         @order = @LONCAPA::map::order;
                   18283:         @resparms = @LONCAPA::map::resparms;
                   18284:         @zombies = @LONCAPA::map::zombies;
                   18285:     }
1.1308    raeburn  18286:     my $suppmap = 'supplemental.sequence';
                   18287:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   18288:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   18289:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  18290:     if ($keeporder) {
                   18291:         @LONCAPA::map::resources = @resources;
                   18292:         @LONCAPA::map::order = @order;
                   18293:         @LONCAPA::map::resparms = @resparms;
                   18294:         @LONCAPA::map::zombies = @zombies;
                   18295:     }
1.1308    raeburn  18296:     if ($supptools) {
                   18297:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18298:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18299:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18300:         }
                   18301:     }
1.1083    raeburn  18302:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18303:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18304:     }
                   18305:     return;
                   18306: }
                   18307: 
1.1110    raeburn  18308: sub allmaps_incourse {
                   18309:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18310:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18311:         $cid = $env{'request.course.id'};
                   18312:         $cdom = $env{'course.'.$cid.'.domain'};
                   18313:         $cnum = $env{'course.'.$cid.'.num'};
                   18314:         $chome = $env{'course.'.$cid.'.home'};
                   18315:     }
                   18316:     my %allmaps = ();
                   18317:     my $lastchange =
                   18318:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18319:     if ($lastchange > $env{'request.course.tied'}) {
                   18320:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18321:         unless ($ferr) {
1.1326    raeburn  18322:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  18323:         }
                   18324:     }
                   18325:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18326:     if (defined($navmap)) {
                   18327:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18328:             $allmaps{$res->src()} = 1;
                   18329:         }
                   18330:     }
                   18331:     return \%allmaps;
                   18332: }
                   18333: 
1.1083    raeburn  18334: sub parse_supplemental_title {
                   18335:     my ($title) = @_;
                   18336: 
                   18337:     my ($foldertitle,$renametitle);
                   18338:     if ($title =~ /&amp;&amp;&amp;/) {
                   18339:         $title = &HTML::Entites::decode($title);
                   18340:     }
                   18341:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18342:         $renametitle=$4;
                   18343:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18344:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18345:         my $name =  &plainname($uname,$udom);
                   18346:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18347:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18348:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18349:             $name.': <br />'.$foldertitle;
                   18350:     }
                   18351:     if (wantarray) {
                   18352:         return ($title,$foldertitle,$renametitle);
                   18353:     }
                   18354:     return $title;
                   18355: }
                   18356: 
1.1143    raeburn  18357: sub recurse_supplemental {
1.1308    raeburn  18358:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  18359:     if ($suppmap) {
                   18360:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18361:         if ($fatal) {
                   18362:             $errors ++;
                   18363:         } else {
                   18364:             if ($#LONCAPA::map::resources > 0) {
                   18365:                 foreach my $res (@LONCAPA::map::resources) {
                   18366:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   18367:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  18368:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  18369:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   18370:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  18371:                         } else {
1.1308    raeburn  18372:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   18373:                                 $numexttools ++;
                   18374:                             }
1.1143    raeburn  18375:                             $numfiles ++;
                   18376:                         }
                   18377:                     }
                   18378:                 }
                   18379:             }
                   18380:         }
                   18381:     }
1.1308    raeburn  18382:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  18383: }
                   18384: 
1.1101    raeburn  18385: sub symb_to_docspath {
1.1267    raeburn  18386:     my ($symb,$navmapref) = @_;
                   18387:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18388:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18389:     if ($resurl=~/\.(sequence|page)$/) {
                   18390:         $mapurl=$resurl;
                   18391:     } elsif ($resurl eq 'adm/navmaps') {
                   18392:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18393:     }
                   18394:     my $mapresobj;
1.1267    raeburn  18395:     unless (ref($$navmapref)) {
                   18396:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18397:     }
                   18398:     if (ref($$navmapref)) {
                   18399:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18400:     }
                   18401:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18402:     my $type=$2;
                   18403:     my $path;
                   18404:     if (ref($mapresobj)) {
                   18405:         my $pcslist = $mapresobj->map_hierarchy();
                   18406:         if ($pcslist ne '') {
                   18407:             foreach my $pc (split(/,/,$pcslist)) {
                   18408:                 next if ($pc <= 1);
1.1267    raeburn  18409:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18410:                 if (ref($res)) {
                   18411:                     my $thisurl = $res->src();
                   18412:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18413:                     my $thistitle = $res->title();
                   18414:                     $path .= '&'.
                   18415:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18416:                              &escape($thistitle).
1.1101    raeburn  18417:                              ':'.$res->randompick().
                   18418:                              ':'.$res->randomout().
                   18419:                              ':'.$res->encrypted().
                   18420:                              ':'.$res->randomorder().
                   18421:                              ':'.$res->is_page();
                   18422:                 }
                   18423:             }
                   18424:         }
                   18425:         $path =~ s/^\&//;
                   18426:         my $maptitle = $mapresobj->title();
                   18427:         if ($mapurl eq 'default') {
1.1129    raeburn  18428:             $maptitle = 'Main Content';
1.1101    raeburn  18429:         }
                   18430:         $path .= (($path ne '')? '&' : '').
                   18431:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18432:                  &escape($maptitle).
1.1101    raeburn  18433:                  ':'.$mapresobj->randompick().
                   18434:                  ':'.$mapresobj->randomout().
                   18435:                  ':'.$mapresobj->encrypted().
                   18436:                  ':'.$mapresobj->randomorder().
                   18437:                  ':'.$mapresobj->is_page();
                   18438:     } else {
                   18439:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18440:         my $ispage = (($type eq 'page')? 1 : '');
                   18441:         if ($mapurl eq 'default') {
1.1129    raeburn  18442:             $maptitle = 'Main Content';
1.1101    raeburn  18443:         }
                   18444:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18445:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18446:     }
                   18447:     unless ($mapurl eq 'default') {
                   18448:         $path = 'default&'.
1.1146    raeburn  18449:                 &escape('Main Content').
1.1101    raeburn  18450:                 ':::::&'.$path;
                   18451:     }
                   18452:     return $path;
                   18453: }
                   18454: 
1.1094    raeburn  18455: sub captcha_display {
1.1327    raeburn  18456:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18457:     my ($output,$error);
1.1234    raeburn  18458:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18459:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18460:     if ($captcha eq 'original') {
1.1094    raeburn  18461:         $output = &create_captcha();
                   18462:         unless ($output) {
1.1172    raeburn  18463:             $error = 'captcha';
1.1094    raeburn  18464:         }
                   18465:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18466:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18467:         unless ($output) {
1.1172    raeburn  18468:             $error = 'recaptcha';
1.1094    raeburn  18469:         }
                   18470:     }
1.1234    raeburn  18471:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18472: }
                   18473: 
                   18474: sub captcha_response {
1.1327    raeburn  18475:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18476:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18477:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18478:     if ($captcha eq 'original') {
1.1094    raeburn  18479:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18480:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18481:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18482:     } else {
                   18483:         $captcha_chk = 1;
                   18484:     }
                   18485:     return ($captcha_chk,$captcha_error);
                   18486: }
                   18487: 
                   18488: sub get_captcha_config {
1.1327    raeburn  18489:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18490:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18491:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18492:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18493:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18494:     if ($context eq 'usercreation') {
                   18495:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18496:         if (ref($domconfig{$context}) eq 'HASH') {
                   18497:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18498:             if (ref($hashtocheck) eq 'HASH') {
                   18499:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18500:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18501:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18502:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18503:                     }
                   18504:                     if ($privkey && $pubkey) {
                   18505:                         $captcha = 'recaptcha';
1.1234    raeburn  18506:                         $version = $hashtocheck->{'recaptchaversion'};
                   18507:                         if ($version ne '2') {
                   18508:                             $version = 1;
                   18509:                         }
1.1095    raeburn  18510:                     } else {
                   18511:                         $captcha = 'original';
                   18512:                     }
                   18513:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18514:                     $captcha = 'original';
                   18515:                 }
1.1094    raeburn  18516:             }
1.1095    raeburn  18517:         } else {
                   18518:             $captcha = 'captcha';
                   18519:         }
                   18520:     } elsif ($context eq 'login') {
                   18521:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18522:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18523:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18524:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18525:             if ($privkey && $pubkey) {
                   18526:                 $captcha = 'recaptcha';
1.1234    raeburn  18527:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18528:                 if ($version ne '2') {
                   18529:                     $version = 1; 
                   18530:                 }
1.1095    raeburn  18531:             } else {
                   18532:                 $captcha = 'original';
1.1094    raeburn  18533:             }
1.1095    raeburn  18534:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18535:             $captcha = 'original';
1.1094    raeburn  18536:         }
1.1327    raeburn  18537:     } elsif ($context eq 'passwords') {
                   18538:         if ($dom_in_effect) {
                   18539:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18540:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18541:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18542:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18543:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18544:                 }
                   18545:                 if ($privkey && $pubkey) {
                   18546:                     $captcha = 'recaptcha';
                   18547:                     $version = $passwdconf{'recaptchaversion'};
                   18548:                     if ($version ne '2') {
                   18549:                         $version = 1;
                   18550:                     }
                   18551:                 } else {
                   18552:                     $captcha = 'original';
                   18553:                 }
                   18554:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18555:                 $captcha = 'original';
                   18556:             }
                   18557:         }
                   18558:     } 
1.1234    raeburn  18559:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18560: }
                   18561: 
                   18562: sub create_captcha {
                   18563:     my %captcha_params = &captcha_settings();
                   18564:     my ($output,$maxtries,$tries) = ('',10,0);
                   18565:     while ($tries < $maxtries) {
                   18566:         $tries ++;
                   18567:         my $captcha = Authen::Captcha->new (
                   18568:                                            output_folder => $captcha_params{'output_dir'},
                   18569:                                            data_folder   => $captcha_params{'db_dir'},
                   18570:                                           );
                   18571:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18572: 
                   18573:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18574:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  18575:                       '<span class="LC_nobreak">'.
1.1094    raeburn  18576:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18577:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1367    raeburn  18578:                       '</span><br />'.
1.1176    raeburn  18579:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18580:             last;
                   18581:         }
                   18582:     }
1.1323    raeburn  18583:     if ($output eq '') {
                   18584:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18585:     }
1.1094    raeburn  18586:     return $output;
                   18587: }
                   18588: 
                   18589: sub captcha_settings {
                   18590:     my %captcha_params = (
                   18591:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18592:                            www_output_dir => "/captchaspool",
                   18593:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18594:                            numchars       => '5',
                   18595:                          );
                   18596:     return %captcha_params;
                   18597: }
                   18598: 
                   18599: sub check_captcha {
                   18600:     my ($captcha_chk,$captcha_error);
                   18601:     my $code = $env{'form.code'};
                   18602:     my $md5sum = $env{'form.crypt'};
                   18603:     my %captcha_params = &captcha_settings();
                   18604:     my $captcha = Authen::Captcha->new(
                   18605:                       output_folder => $captcha_params{'output_dir'},
                   18606:                       data_folder   => $captcha_params{'db_dir'},
                   18607:                   );
1.1109    raeburn  18608:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18609:     my %captcha_hash = (
                   18610:                         0       => 'Code not checked (file error)',
                   18611:                        -1      => 'Failed: code expired',
                   18612:                        -2      => 'Failed: invalid code (not in database)',
                   18613:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18614:     );
                   18615:     if ($captcha_chk != 1) {
                   18616:         $captcha_error = $captcha_hash{$captcha_chk}
                   18617:     }
                   18618:     return ($captcha_chk,$captcha_error);
                   18619: }
                   18620: 
                   18621: sub create_recaptcha {
1.1234    raeburn  18622:     my ($pubkey,$version) = @_;
                   18623:     if ($version >= 2) {
1.1367    raeburn  18624:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18625:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  18626:     } else {
                   18627:         my $use_ssl;
                   18628:         if ($ENV{'SERVER_PORT'} == 443) {
                   18629:             $use_ssl = 1;
                   18630:         }
                   18631:         my $captcha = Captcha::reCAPTCHA->new;
                   18632:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18633:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18634:                &mt('If the text is hard to read, [_1] will replace them.',
                   18635:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18636:                '<br /><br />';
                   18637:     }
1.1094    raeburn  18638: }
                   18639: 
                   18640: sub check_recaptcha {
1.1234    raeburn  18641:     my ($privkey,$version) = @_;
1.1094    raeburn  18642:     my $captcha_chk;
1.1350    raeburn  18643:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18644:     if ($version >= 2) {
                   18645:         my %info = (
                   18646:                      secret   => $privkey, 
                   18647:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18648:                      remoteip => $ip,
1.1234    raeburn  18649:                    );
1.1280    raeburn  18650:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18651:         $request->content(join('&',map {
                   18652:                          my $name = escape($_);
                   18653:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18654:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18655:                          : &escape($info{$_}) );
                   18656:         } keys(%info)));
                   18657:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18658:         if ($response->is_success)  {
                   18659:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18660:             if (ref($data) eq 'HASH') {
                   18661:                 if ($data->{'success'}) {
                   18662:                     $captcha_chk = 1;
                   18663:                 }
                   18664:             }
                   18665:         }
                   18666:     } else {
                   18667:         my $captcha = Captcha::reCAPTCHA->new;
                   18668:         my $captcha_result =
                   18669:             $captcha->check_answer(
                   18670:                                     $privkey,
1.1350    raeburn  18671:                                     $ip,
1.1234    raeburn  18672:                                     $env{'form.recaptcha_challenge_field'},
                   18673:                                     $env{'form.recaptcha_response_field'},
                   18674:                                   );
                   18675:         if ($captcha_result->{is_valid}) {
                   18676:             $captcha_chk = 1;
                   18677:         }
1.1094    raeburn  18678:     }
                   18679:     return $captcha_chk;
                   18680: }
                   18681: 
1.1174    raeburn  18682: sub emailusername_info {
1.1244    raeburn  18683:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18684:     my %titles = &Apache::lonlocal::texthash (
                   18685:                      lastname      => 'Last Name',
                   18686:                      firstname     => 'First Name',
                   18687:                      institution   => 'School/college/university',
                   18688:                      location      => "School's city, state/province, country",
                   18689:                      web           => "School's web address",
                   18690:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18691:                      id            => 'Student/Employee ID',
1.1174    raeburn  18692:                  );
                   18693:     return (\@fields,\%titles);
                   18694: }
                   18695: 
1.1161    raeburn  18696: sub cleanup_html {
                   18697:     my ($incoming) = @_;
                   18698:     my $outgoing;
                   18699:     if ($incoming ne '') {
                   18700:         $outgoing = $incoming;
                   18701:         $outgoing =~ s/;/&#059;/g;
                   18702:         $outgoing =~ s/\#/&#035;/g;
                   18703:         $outgoing =~ s/\&/&#038;/g;
                   18704:         $outgoing =~ s/</&#060;/g;
                   18705:         $outgoing =~ s/>/&#062;/g;
                   18706:         $outgoing =~ s/\(/&#040/g;
                   18707:         $outgoing =~ s/\)/&#041;/g;
                   18708:         $outgoing =~ s/"/&#034;/g;
                   18709:         $outgoing =~ s/'/&#039;/g;
                   18710:         $outgoing =~ s/\$/&#036;/g;
                   18711:         $outgoing =~ s{/}{&#047;}g;
                   18712:         $outgoing =~ s/=/&#061;/g;
                   18713:         $outgoing =~ s/\\/&#092;/g
                   18714:     }
                   18715:     return $outgoing;
                   18716: }
                   18717: 
1.1190    musolffc 18718: # Checks for critical messages and returns a redirect url if one exists.
                   18719: # $interval indicates how often to check for messages.
1.1282    raeburn  18720: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18721: sub critical_redirect {
1.1282    raeburn  18722:     my ($interval,$context) = @_;
1.1356    raeburn  18723:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18724:         return ();
                   18725:     }
1.1190    musolffc 18726:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18727:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18728:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18729:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  18730:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18731:             if ($blocked) {
                   18732:                 my $checkrole = "cm./$cdom/$cnum";
                   18733:                 if ($env{'request.course.sec'} ne '') {
                   18734:                     $checkrole .= "/$env{'request.course.sec'}";
                   18735:                 }
                   18736:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18737:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18738:                     return;
                   18739:                 }
                   18740:             }
                   18741:         }
1.1190    musolffc 18742:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18743:                                         $env{'user.name'});
                   18744:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18745:         my $redirecturl;
1.1190    musolffc 18746:         if ($what[0]) {
1.1356    raeburn  18747: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 18748: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18749: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18750:                 return (1, $url);
1.1190    musolffc 18751:             }
1.1191    raeburn  18752:         }
                   18753:     } 
                   18754:     return ();
1.1190    musolffc 18755: }
                   18756: 
1.1174    raeburn  18757: # Use:
                   18758: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18759: #
                   18760: ##################################################
                   18761: #          password associated functions         #
                   18762: ##################################################
                   18763: sub des_keys {
                   18764:     # Make a new key for DES encryption.
                   18765:     # Each key has two parts which are returned separately.
                   18766:     # Please note:  Each key must be passed through the &hex function
                   18767:     # before it is output to the web browser.  The hex versions cannot
                   18768:     # be used to decrypt.
                   18769:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18770:                 '8','9','a','b','c','d','e','f');
                   18771:     my $lkey='';
                   18772:     for (0..7) {
                   18773:         $lkey.=$hexstr[rand(15)];
                   18774:     }
                   18775:     my $ukey='';
                   18776:     for (0..7) {
                   18777:         $ukey.=$hexstr[rand(15)];
                   18778:     }
                   18779:     return ($lkey,$ukey);
                   18780: }
                   18781: 
                   18782: sub des_decrypt {
                   18783:     my ($key,$cyphertext) = @_;
                   18784:     my $keybin=pack("H16",$key);
                   18785:     my $cypher;
                   18786:     if ($Crypt::DES::VERSION>=2.03) {
                   18787:         $cypher=new Crypt::DES $keybin;
                   18788:     } else {
                   18789:         $cypher=new DES $keybin;
                   18790:     }
1.1233    raeburn  18791:     my $plaintext='';
                   18792:     my $cypherlength = length($cyphertext);
                   18793:     my $numchunks = int($cypherlength/32);
                   18794:     for (my $j=0; $j<$numchunks; $j++) {
                   18795:         my $start = $j*32;
                   18796:         my $cypherblock = substr($cyphertext,$start,32);
                   18797:         my $chunk =
                   18798:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18799:         $chunk .=
                   18800:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18801:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18802:         $plaintext .= $chunk;
                   18803:     }
1.1174    raeburn  18804:     return $plaintext;
                   18805: }
                   18806: 
1.1344    raeburn  18807: sub get_requested_shorturls {
1.1309    raeburn  18808:     my ($cdom,$cnum,$navmap) = @_;
                   18809:     return unless (ref($navmap));
1.1344    raeburn  18810:     my ($numnew,$errors);
1.1309    raeburn  18811:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18812:     if (@toshorten) {
                   18813:         my (%maps,%resources,%titles);
                   18814:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18815:                                                                'shorturls',$cdom,$cnum);
                   18816:         if (keys(%resources)) {
1.1344    raeburn  18817:             my %tocreate;
1.1309    raeburn  18818:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18819:                 my $symb = $resources{$item};
                   18820:                 if ($symb) {
                   18821:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18822:                 }
                   18823:             }
1.1344    raeburn  18824:             if (keys(%tocreate)) {
                   18825:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18826:                                                       \%tocreate);
                   18827:             }
1.1309    raeburn  18828:         }
1.1344    raeburn  18829:     }
                   18830:     return ($numnew,$errors);
                   18831: }
                   18832: 
                   18833: sub make_short_symbs {
                   18834:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18835:     my ($numnew,@errors);
                   18836:     if (ref($tocreateref) eq 'HASH') {
                   18837:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18838:         if (keys(%tocreate)) {
                   18839:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18840:             my $su = Short::URL->new(no_vowels => 1);
                   18841:             my $init = '';
                   18842:             my (%newunique,%addcourse,%courseonly,%failed);
                   18843:             # get lock on tiny db
                   18844:             my $now = time;
1.1344    raeburn  18845:             if ($lockuser eq '') {
                   18846:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18847:             }
1.1309    raeburn  18848:             my $lockhash = {
1.1344    raeburn  18849:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18850:                             };
                   18851:             my $tries = 0;
                   18852:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18853:             my ($code,$error);
                   18854:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18855:                 $tries ++;
                   18856:                 sleep 1;
1.1319    raeburn  18857:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18858:             }
                   18859:             if ($gotlock eq 'ok') {
                   18860:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18861:                                        \%addcourse,\%courseonly,\%failed);
                   18862:                 if (keys(%failed)) {
                   18863:                     my $numfailed = scalar(keys(%failed));
                   18864:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18865:                 }
                   18866:                 if (keys(%newunique)) {
                   18867:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18868:                     if ($putres eq 'ok') {
                   18869:                         $numnew = scalar(keys(%newunique));
                   18870:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18871:                         unless ($newputres eq 'ok') {
                   18872:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18873:                         }
                   18874:                     } else {
                   18875:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18876:                     }
                   18877:                 }
                   18878:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18879:                 unless ($dellockres eq 'ok') {
                   18880:                     push(@errors,&mt('error: could not release lockfile'));
                   18881:                 }
                   18882:             } else {
                   18883:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18884:             }
                   18885:             if (keys(%courseonly)) {
                   18886:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18887:                 if ($result ne 'ok') {
                   18888:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18889:                 }
                   18890:             }
                   18891:         }
                   18892:     }
                   18893:     return ($numnew,\@errors);
                   18894: }
                   18895: 
                   18896: sub shorten_symbs {
                   18897:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18898:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18899:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18900:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18901:     my (%possibles,%collisions);
                   18902:     foreach my $key (keys(%{$tocreate})) {
                   18903:         my $num = String::CRC32::crc32($key);
                   18904:         my $tiny = $su->encode($num,$init);
                   18905:         if ($tiny) {
                   18906:             $possibles{$tiny} = $key;
                   18907:         }
                   18908:     }
                   18909:     if (!$init) {
                   18910:         $init = 1;
                   18911:     } else {
                   18912:         $init ++;
                   18913:     }
                   18914:     if (keys(%possibles)) {
                   18915:         my @posstiny = keys(%possibles);
                   18916:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18917:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18918:         if (keys(%currtiny)) {
                   18919:             foreach my $key (keys(%currtiny)) {
                   18920:                 next if ($currtiny{$key} eq '');
                   18921:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18922:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18923:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18924:                         $courseonly->{$tsymb} = $key;
                   18925:                     }
                   18926:                 } else {
                   18927:                     $collisions{$possibles{$key}} = 1;
                   18928:                 }
                   18929:                 delete($possibles{$key});
                   18930:             }
                   18931:         }
                   18932:         foreach my $key (keys(%possibles)) {
                   18933:             $newunique->{$key} = $possibles{$key};
                   18934:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18935:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18936:                 $addcourse->{$tsymb} = $key;
                   18937:             }
                   18938:         }
                   18939:     }
                   18940:     if (keys(%collisions)) {
                   18941:         if ($init <5) {
                   18942:             if (!$init) {
                   18943:                 $init = 1;
                   18944:             } else {
                   18945:                 $init ++;
                   18946:             }
                   18947:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18948:                                    $newunique,$addcourse,$courseonly,$failed);
                   18949:         } else {
                   18950:             foreach my $key (keys(%collisions)) {
                   18951:                 $failed->{$key} = 1;
                   18952:             }
                   18953:         }
                   18954:     }
                   18955:     return $init;
                   18956: }
                   18957: 
1.1328    raeburn  18958: sub is_nonframeable {
1.1329    raeburn  18959:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18960:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18961:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18962: 
                   18963:     $remprotocol = lc($remprotocol);
                   18964:     $remhost = lc($remhost);
                   18965:     my $remport = 80;
                   18966:     if ($remprotocol eq 'https') {
                   18967:         $remport = 443;
                   18968:     }
1.1330    raeburn  18969:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18970:     if ($cached) {
                   18971:         unless ($nocache) {
                   18972:             if ($result) {
                   18973:                 return 1;
                   18974:             } else {
                   18975:                 return 0;
                   18976:             }
                   18977:         }
                   18978:     }
1.1328    raeburn  18979:     my $uselink;
                   18980:     my $request = new HTTP::Request('HEAD',$url);
                   18981:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18982:     if ($response->is_success()) {
                   18983:         my $secpolicy = lc($response->header('content-security-policy'));
                   18984:         my $xframeop = lc($response->header('x-frame-options'));
                   18985:         $secpolicy =~ s/^\s+|\s+$//g;
                   18986:         $xframeop =~ s/^\s+|\s+$//g;
                   18987:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18988:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18989:             my ($origin,$protocol,$port);
                   18990:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18991:                 $port = $ENV{'SERVER_PORT'};
                   18992:             } else {
                   18993:                 $port = 80;
                   18994:             }
                   18995:             if ($absolute eq '') {
                   18996:                 $protocol = 'http:';
                   18997:                 if ($port == 443) {
                   18998:                     $protocol = 'https:';
                   18999:                 }
                   19000:                 $origin = $protocol.'//'.lc($hostname);
                   19001:             } else {
                   19002:                 $origin = lc($absolute);
                   19003:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19004:             }
                   19005:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19006:                 my $framepolicy = $1;
                   19007:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19008:                 my @policies = split(/\s+/,$framepolicy);
                   19009:                 if (@policies) {
                   19010:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19011:                         $uselink = 1;
                   19012:                     } else {
                   19013:                         $uselink = 1;
                   19014:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19015:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19016:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19017:                             undef($uselink);
                   19018:                         }
                   19019:                         if ($uselink) {
                   19020:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19021:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19022:                                     undef($uselink);
                   19023:                                 }
                   19024:                             }
                   19025:                         }
                   19026:                         if ($uselink) {
                   19027:                             my @possok;
                   19028:                             if ($ip ne '') {
                   19029:                                 push(@possok,$ip);
                   19030:                             }
                   19031:                             my $hoststr = '';
                   19032:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19033:                                 if ($hoststr eq '') {
                   19034:                                     $hoststr = $part;
                   19035:                                 } else {
                   19036:                                     $hoststr = "$part.$hoststr";
                   19037:                                 }
                   19038:                                 if ($hoststr eq $hostname) {
                   19039:                                     push(@possok,$hostname);
                   19040:                                 } else {
                   19041:                                     push(@possok,"*.$hoststr");
                   19042:                                 }
                   19043:                             }
                   19044:                             if (@possok) {
                   19045:                                 foreach my $poss (@possok) {
                   19046:                                     last if (!$uselink);
                   19047:                                     foreach my $policy (@policies) {
                   19048:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19049:                                             undef($uselink);
                   19050:                                             last;
                   19051:                                         }
                   19052:                                     }
                   19053:                                 }
                   19054:                             }
                   19055:                         }
                   19056:                     }
                   19057:                 }
                   19058:             } elsif ($xframeop ne '') {
                   19059:                 $uselink = 1;
                   19060:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19061:                 if (@policies) {
                   19062:                     unless (grep(/^deny$/,@policies)) {
                   19063:                         if ($origin ne '') {
                   19064:                             if (grep(/^sameorigin$/,@policies)) {
                   19065:                                 if ($remotehost eq $origin) {
                   19066:                                     undef($uselink);
                   19067:                                 }
                   19068:                             }
                   19069:                             if ($uselink) {
                   19070:                                 foreach my $policy (@policies) {
                   19071:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19072:                                         my $allowfrom = $1;
                   19073:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19074:                                             undef($uselink);
                   19075:                                             last;
                   19076:                                         }
                   19077:                                     }
                   19078:                                 }
                   19079:                             }
                   19080:                         }
                   19081:                     }
                   19082:                 }
                   19083:             }
                   19084:         }
                   19085:     }
1.1329    raeburn  19086:     if ($nocache) {
                   19087:         if ($cached) {
                   19088:             my $devalidate;
                   19089:             if ($uselink && !$result) {
                   19090:                 $devalidate = 1;
                   19091:             } elsif (!$uselink && $result) {
                   19092:                 $devalidate = 1;
                   19093:             }
                   19094:             if ($devalidate) {
                   19095:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19096:             }
                   19097:         }
                   19098:     } else {
                   19099:         if ($uselink) {
                   19100:             $result = 1;
                   19101:         } else {
                   19102:             $result = 0;
                   19103:         }
                   19104:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19105:     }
1.1328    raeburn  19106:     return $uselink;
                   19107: }
                   19108: 
1.1359    raeburn  19109: sub page_menu {
                   19110:     my ($menucolls,$menunum) = @_;
                   19111:     my %menu;
                   19112:     foreach my $item (split(/;/,$menucolls)) {
                   19113:         my ($num,$value) = split(/\%/,$item);
                   19114:         if ($num eq $menunum) {
                   19115:             my @entries = split(/\&/,$value);
                   19116:             foreach my $entry (@entries) {
                   19117:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19118:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19119:                     $menu{$name} = $fields;
                   19120:                 } else {
                   19121:                     my @shown;
                   19122:                     if ($fields =~ /,/) {
                   19123:                         @shown = split(/,/,$fields);
                   19124:                     } else {
                   19125:                         @shown = ($fields);
                   19126:                     }
                   19127:                     if (@shown) {
                   19128:                         foreach my $field (@shown) {
                   19129:                             next if ($field eq '');
                   19130:                             $menu{$field} = 1;
                   19131:                         }
                   19132:                     }
                   19133:                 }
                   19134:             }
                   19135:         }
                   19136:     }
                   19137:     return %menu;
                   19138: }
                   19139: 
1.112     bowersj2 19140: 1;
                   19141: __END__;
1.41      ng       19142: 

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