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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1346  ! raeburn     4: # $Id: loncommon.pm,v 1.1345 2020/08/10 19:28:21 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.1309    raeburn    89: use String::CRC32();
                     90: use Short::URL();
1.117     www        91: 
1.517     raeburn    92: # ---------------------------------------------- Designs
                     93: use vars qw(%defaultdesign);
                     94: 
1.22      www        95: my $readit;
                     96: 
1.517     raeburn    97: 
1.157     matthew    98: ##
                     99: ## Global Variables
                    100: ##
1.46      matthew   101: 
1.643     foxr      102: 
                    103: # ----------------------------------------------- SSI with retries:
                    104: #
                    105: 
                    106: =pod
                    107: 
1.648     raeburn   108: =head1 Server Side include with retries:
1.643     foxr      109: 
                    110: =over 4
                    111: 
1.648     raeburn   112: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      113: 
                    114: Performs an ssi with some number of retries.  Retries continue either
                    115: until the result is ok or until the retry count supplied by the
                    116: caller is exhausted.  
                    117: 
                    118: Inputs:
1.648     raeburn   119: 
                    120: =over 4
                    121: 
1.643     foxr      122: resource   - Identifies the resource to insert.
1.648     raeburn   123: 
1.643     foxr      124: retries    - Count of the number of retries allowed.
1.648     raeburn   125: 
1.643     foxr      126: form       - Hash that identifies the rendering options.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: Returns:
                    131: 
                    132: =over 4
                    133: 
1.643     foxr      134: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   135: 
1.643     foxr      136: response   - The response from the last attempt (which may or may not have been successful.
                    137: 
1.648     raeburn   138: =back
                    139: 
                    140: =back
                    141: 
1.643     foxr      142: =cut
                    143: 
                    144: sub ssi_with_retries {
                    145:     my ($resource, $retries, %form) = @_;
                    146: 
                    147: 
                    148:     my $ok = 0;			# True if we got a good response.
                    149:     my $content;
                    150:     my $response;
                    151: 
                    152:     # Try to get the ssi done. within the retries count:
                    153: 
                    154:     do {
                    155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    156: 	$ok      = $response->is_success;
1.650     www       157:         if (!$ok) {
                    158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    159:         }
1.643     foxr      160: 	$retries--;
                    161:     } while (!$ok && ($retries > 0));
                    162: 
                    163:     if (!$ok) {
                    164: 	$content = '';		# On error return an empty content.
                    165:     }
                    166:     return ($content, $response);
                    167: 
                    168: }
                    169: 
                    170: 
                    171: 
1.20      www       172: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  173: my %language;
1.124     www       174: my %supported_language;
1.1088    foxr      175: my %supported_codes;
1.1048    foxr      176: my %latex_language;		# For choosing hyphenation in <transl..>
                    177: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  178: my %cprtag;
1.192     taceyjo1  179: my %scprtag;
1.351     www       180: my %fe; my %fd; my %fm;
1.41      ng        181: my %category_extensions;
1.12      harris41  182: 
1.46      matthew   183: # ---------------------------------------------- Thesaurus variables
1.144     matthew   184: #
                    185: # %Keywords:
                    186: #      A hash used by &keyword to determine if a word is considered a keyword.
                    187: # $thesaurus_db_file 
                    188: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   189: 
                    190: my %Keywords;
                    191: my $thesaurus_db_file;
                    192: 
1.144     matthew   193: #
                    194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    195: # thesaurus.tab, and filecategories.tab.
                    196: #
1.18      www       197: BEGIN {
1.46      matthew   198:     # Variable initialization
                    199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    200:     #
1.22      www       201:     unless ($readit) {
1.12      harris41  202: # ------------------------------------------------------------------- languages
                    203:     {
1.158     raeburn   204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    205:                                    '/language.tab';
1.1317    raeburn   206:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  207:             while (my $line = <$fh>) {
                    208:                 next if ($line=~/^\#/);
                    209:                 chomp($line);
1.1088    foxr      210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   211:                 $language{$key}=$val.' - '.$enc;
                    212:                 if ($sup) {
                    213:                     $supported_language{$key}=$sup;
1.1088    foxr      214: 		    $supported_codes{$key}   = $code;
1.158     raeburn   215:                 }
1.1048    foxr      216: 		if ($latex) {
                    217: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      218: 		    $latex_language{$code} = $latex;
1.1048    foxr      219: 		}
1.158     raeburn   220:             }
                    221:             close($fh);
                    222:         }
1.12      harris41  223:     }
                    224: # ------------------------------------------------------------------ copyrights
                    225:     {
1.158     raeburn   226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    227:                                   '/copyright.tab';
1.1317    raeburn   228:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  229:             while (my $line = <$fh>) {
                    230:                 next if ($line=~/^\#/);
                    231:                 chomp($line);
                    232:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   233:                 $cprtag{$key}=$val;
                    234:             }
                    235:             close($fh);
                    236:         }
1.12      harris41  237:     }
1.351     www       238: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  239:     {
                    240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    241:                                   '/source_copyright.tab';
1.1317    raeburn   242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  243:             while (my $line = <$fh>) {
                    244:                 next if ($line =~ /^\#/);
                    245:                 chomp($line);
                    246:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  247:                 $scprtag{$key}=$val;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251:     }
1.63      www       252: 
1.517     raeburn   253: # -------------------------------------------------------------- default domain designs
1.63      www       254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   255:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   256:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   257:         while (my $line = <$fh>) {
                    258:             next if ($line =~ /^\#/);
                    259:             chomp($line);
                    260:             my ($key,$val)=(split(/\=/,$line));
                    261:             if ($val) { $defaultdesign{$key}=$val; }
                    262:         }
                    263:         close($fh);
1.63      www       264:     }
                    265: 
1.15      harris41  266: # ------------------------------------------------------------- file categories
                    267:     {
1.158     raeburn   268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                                   '/filecategories.tab';
1.1317    raeburn   270:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  271: 	    while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   275:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   276:             }
                    277:             close($fh);
                    278:         }
                    279: 
1.15      harris41  280:     }
1.12      harris41  281: # ------------------------------------------------------------------ file types
                    282:     {
1.158     raeburn   283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    284:                '/filetypes.tab';
1.1317    raeburn   285:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  286:             while (my $line = <$fh>) {
                    287: 		next if ($line =~ /^\#/);
                    288: 		chomp($line);
                    289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   290:                 if ($descr ne '') {
                    291:                     $fe{$ending}=lc($emb);
                    292:                     $fd{$ending}=$descr;
1.351     www       293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   294:                 }
                    295:             }
                    296:             close($fh);
                    297:         }
1.12      harris41  298:     }
1.22      www       299:     &Apache::lonnet::logthis(
1.705     tempelho  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       301:     $readit=1;
1.46      matthew   302:     }  # end of unless($readit) 
1.32      matthew   303:     
                    304: }
1.112     bowersj2  305: 
1.42      matthew   306: ###############################################################
                    307: ##           HTML and Javascript Helper Functions            ##
                    308: ###############################################################
                    309: 
                    310: =pod 
                    311: 
1.112     bowersj2  312: =head1 HTML and Javascript Functions
1.42      matthew   313: 
1.112     bowersj2  314: =over 4
                    315: 
1.648     raeburn   316: =item * &browser_and_searcher_javascript()
1.112     bowersj2  317: 
                    318: X<browsing, javascript>X<searching, javascript>Returns a string
                    319: containing javascript with two functions, C<openbrowser> and
                    320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    321: tags.
1.42      matthew   322: 
1.648     raeburn   323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   324: 
                    325: inputs: formname, elementname, only, omit
                    326: 
                    327: formname and elementname indicate the name of the html form and name of
                    328: the element that the results of the browsing selection are to be placed in. 
                    329: 
                    330: Specifying 'only' will restrict the browser to displaying only files
1.185     www       331: with the given extension.  Can be a comma separated list.
1.42      matthew   332: 
                    333: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       334: with the given extension.  Can be a comma separated list.
1.42      matthew   335: 
1.648     raeburn   336: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   337: 
                    338: Inputs: formname, elementname
                    339: 
                    340: formname and elementname specify the name of the html form and the name
                    341: of the element the selection from the search results will be placed in.
1.542     raeburn   342: 
1.42      matthew   343: =cut
                    344: 
                    345: sub browser_and_searcher_javascript {
1.199     albertel  346:     my ($mode)=@_;
                    347:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  348:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   349:     return <<END;
1.219     albertel  350: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   351:     var editbrowser = null;
1.135     albertel  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       353:         var url = '$resurl/?';
1.42      matthew   354:         if (editbrowser == null) {
                    355:             url += 'launch=1&';
                    356:         }
                    357:         url += 'catalogmode=interactive&';
1.199     albertel  358:         url += 'mode=$mode&';
1.611     albertel  359:         url += 'inhibitmenu=yes&';
1.42      matthew   360:         url += 'form=' + formname + '&';
                    361:         if (only != null) {
                    362:             url += 'only=' + only + '&';
1.217     albertel  363:         } else {
                    364:             url += 'only=&';
                    365: 	}
1.42      matthew   366:         if (omit != null) {
                    367:             url += 'omit=' + omit + '&';
1.217     albertel  368:         } else {
                    369:             url += 'omit=&';
                    370: 	}
1.135     albertel  371:         if (titleelement != null) {
                    372:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  373:         } else {
                    374: 	    url += 'titleelement=&';
                    375: 	}
1.42      matthew   376:         url += 'element=' + elementname + '';
                    377:         var title = 'Browser';
1.435     albertel  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   379:         options += ',width=700,height=600';
                    380:         editbrowser = open(url,title,options,'1');
                    381:         editbrowser.focus();
                    382:     }
                    383:     var editsearcher;
1.135     albertel  384:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   385:         var url = '/adm/searchcat?';
                    386:         if (editsearcher == null) {
                    387:             url += 'launch=1&';
                    388:         }
                    389:         url += 'catalogmode=interactive&';
1.199     albertel  390:         url += 'mode=$mode&';
1.42      matthew   391:         url += 'form=' + formname + '&';
1.135     albertel  392:         if (titleelement != null) {
                    393:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  394:         } else {
                    395: 	    url += 'titleelement=&';
                    396: 	}
1.42      matthew   397:         url += 'element=' + elementname + '';
                    398:         var title = 'Search';
1.435     albertel  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   400:         options += ',width=700,height=600';
                    401:         editsearcher = open(url,title,options,'1');
                    402:         editsearcher.focus();
                    403:     }
1.219     albertel  404: // END LON-CAPA Internal -->
1.42      matthew   405: END
1.170     www       406: }
                    407: 
                    408: sub lastresurl {
1.258     albertel  409:     if ($env{'environment.lastresurl'}) {
                    410: 	return $env{'environment.lastresurl'}
1.170     www       411:     } else {
                    412: 	return '/res';
                    413:     }
                    414: }
                    415: 
                    416: sub storeresurl {
                    417:     my $resurl=&Apache::lonnet::clutter(shift);
                    418:     unless ($resurl=~/^\/res/) { return 0; }
                    419:     $resurl=~s/\/$//;
                    420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       422:     return 1;
1.42      matthew   423: }
                    424: 
1.74      www       425: sub studentbrowser_javascript {
1.111     www       426:    unless (
1.258     albertel  427:             (($env{'request.course.id'}) && 
1.302     albertel  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    430: 					  '/'.$env{'request.course.sec'})
                    431: 	      ))
1.258     albertel  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       433:           ) { return ''; }  
1.74      www       434:    return (<<'ENDSTDBRW');
1.776     bisitz    435: <script type="text/javascript" language="Javascript">
1.824     bisitz    436: // <![CDATA[
1.74      www       437:     var stdeditbrowser;
1.1337    raeburn   438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       439:         var url = '/adm/pickstudent?';
                    440:         var filter;
1.558     albertel  441: 	if (!ignorefilter) {
                    442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    443: 	}
1.74      www       444:         if (filter != null) {
                    445:            if (filter != '') {
                    446:                url += 'filter='+filter+'&';
                    447: 	   }
                    448:         }
                    449:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       450:                                     '&udomelement='+udom+
                    451:                                     '&clicker='+clicker;
1.111     www       452: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   453:         if (courseadv == 'condition') {
                    454:             if (document.getElementById('courseadv')) {
                    455:                 courseadv = document.getElementById('courseadv').value;
                    456:             }
                    457:         }
                    458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       459:         var title = 'Student_Browser';
1.74      www       460:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    461:         options += ',width=700,height=600';
                    462:         stdeditbrowser = open(url,title,options,'1');
                    463:         stdeditbrowser.focus();
                    464:     }
1.824     bisitz    465: // ]]>
1.74      www       466: </script>
                    467: ENDSTDBRW
                    468: }
1.42      matthew   469: 
1.1003    www       470: sub resourcebrowser_javascript {
                    471:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       472:    return (<<'ENDRESBRW');
1.1003    www       473: <script type="text/javascript" language="Javascript">
                    474: // <![CDATA[
                    475:     var reseditbrowser;
1.1004    www       476:     function openresbrowser(formname,reslink) {
1.1005    www       477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       478:         var title = 'Resource_Browser';
                    479:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       480:         options += ',width=700,height=500';
1.1004    www       481:         reseditbrowser = open(url,title,options,'1');
                    482:         reseditbrowser.focus();
1.1003    www       483:     }
                    484: // ]]>
                    485: </script>
1.1004    www       486: ENDRESBRW
1.1003    www       487: }
                    488: 
1.74      www       489: sub selectstudent_link {
1.1337    raeburn   490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  494:    if ($env{'request.course.id'}) {  
1.302     albertel  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    497: 					'/'.$env{'request.course.sec'})) {
1.111     www       498: 	   return '';
                    499:        }
1.999     www       500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   501:        if ($courseadv eq 'only') {
                    502:            $callargs .= ",'',1,'$courseadv'";
                    503:        } elsif ($courseadv eq 'none') {
                    504:            $callargs .= ",'','','$courseadv'";
                    505:        } elsif ($courseadv eq 'condition') {
                    506:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   507:        }
                    508:        return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    510:               &mt('Select User').'</a></span>';
1.74      www       511:    }
1.258     albertel  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       513:        $callargs .= ",'',1"; 
1.793     raeburn   514:        return '<span class="LC_nobreak">'.
                    515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    516:               &mt('Select User').'</a></span>';
1.111     www       517:    }
                    518:    return '';
1.91      www       519: }
                    520: 
1.1004    www       521: sub selectresource_link {
                    522:    my ($form,$reslink,$arg)=@_;
                    523:    
                    524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    526:    unless ($env{'request.course.id'}) { return $arg; }
                    527:    return '<span class="LC_nobreak">'.
                    528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    529:               $arg.'</a></span>';
                    530: }
                    531: 
                    532: 
                    533: 
1.653     raeburn   534: sub authorbrowser_javascript {
                    535:     return <<"ENDAUTHORBRW";
1.776     bisitz    536: <script type="text/javascript" language="JavaScript">
1.824     bisitz    537: // <![CDATA[
1.653     raeburn   538: var stdeditbrowser;
                    539: 
                    540: function openauthorbrowser(formname,udom) {
                    541:     var url = '/adm/pickauthor?';
                    542:     url += 'form='+formname+'&roledom='+udom;
                    543:     var title = 'Author_Browser';
                    544:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    545:     options += ',width=700,height=600';
                    546:     stdeditbrowser = open(url,title,options,'1');
                    547:     stdeditbrowser.focus();
                    548: }
                    549: 
1.824     bisitz    550: // ]]>
1.653     raeburn   551: </script>
                    552: ENDAUTHORBRW
                    553: }
                    554: 
1.91      www       555: sub coursebrowser_javascript {
1.1116    raeburn   556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   557:         $credits_element,$instcode) = @_;
1.932     raeburn   558:     my $wintitle = 'Course_Browser';
1.931     raeburn   559:     if ($crstype eq 'Community') {
1.932     raeburn   560:         $wintitle = 'Community_Browser';
1.909     raeburn   561:     }
1.876     raeburn   562:     my $id_functions = &javascript_index_functions();
                    563:     my $output = '
1.776     bisitz    564: <script type="text/javascript" language="JavaScript">
1.824     bisitz    565: // <![CDATA[
1.468     raeburn   566:     var stdeditbrowser;'."\n";
1.876     raeburn   567: 
                    568:     $output .= <<"ENDSTDBRW";
1.909     raeburn   569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       570:         var url = '/adm/pickcourse?';
1.895     raeburn   571:         var formid = getFormIdByName(formname);
1.876     raeburn   572:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  573:         if (domainfilter != null) {
                    574:            if (domainfilter != '') {
                    575:                url += 'domainfilter='+domainfilter+'&';
                    576: 	   }
                    577:         }
1.91      www       578:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  579: 	                            '&cdomelement='+udom+
                    580:                                     '&cnameelement='+desc;
1.468     raeburn   581:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   582:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   583:                 url += '&roleelement='+extra_element;
                    584:                 if (domainfilter == null || domainfilter == '') {
                    585:                     url += '&domainfilter='+extra_element;
                    586:                 }
1.234     raeburn   587:             }
1.468     raeburn   588:             else {
                    589:                 if (formname == 'portform') {
                    590:                     url += '&setroles='+extra_element;
1.800     raeburn   591:                 } else {
                    592:                     if (formname == 'rules') {
                    593:                         url += '&fixeddom='+extra_element; 
                    594:                     }
1.468     raeburn   595:                 }
                    596:             }     
1.230     raeburn   597:         }
1.909     raeburn   598:         if (type != null && type != '') {
                    599:             url += '&type='+type;
                    600:         }
                    601:         if (type_elem != null && type_elem != '') {
                    602:             url += '&typeelement='+type_elem;
                    603:         }
1.872     raeburn   604:         if (formname == 'ccrs') {
                    605:             var ownername = document.forms[formid].ccuname.value;
                    606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   607:             url += '&cloner='+ownername+':'+ownerdom;
                    608:             if (type == 'Course') {
                    609:                 url += '&crscode='+document.forms[formid].crscode.value;
                    610:             }
1.1221    raeburn   611:         }
                    612:         if (formname == 'requestcrs') {
                    613:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   614:         }
1.293     raeburn   615:         if (multflag !=null && multflag != '') {
                    616:             url += '&multiple='+multflag;
                    617:         }
1.909     raeburn   618:         var title = '$wintitle';
1.91      www       619:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    620:         options += ',width=700,height=600';
                    621:         stdeditbrowser = open(url,title,options,'1');
                    622:         stdeditbrowser.focus();
                    623:     }
1.876     raeburn   624: $id_functions
                    625: ENDSTDBRW
1.1116    raeburn   626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    628:                                       $credits_element);
1.876     raeburn   629:     }
                    630:     $output .= '
                    631: // ]]>
                    632: </script>';
                    633:     return $output;
                    634: }
                    635: 
                    636: sub javascript_index_functions {
                    637:     return <<"ENDJS";
                    638: 
                    639: function getFormIdByName(formname) {
                    640:     for (var i=0;i<document.forms.length;i++) {
                    641:         if (document.forms[i].name == formname) {
                    642:             return i;
                    643:         }
                    644:     }
                    645:     return -1;
                    646: }
                    647: 
                    648: function getIndexByName(formid,item) {
                    649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    650:         if (document.forms[formid].elements[i].name == item) {
                    651:             return i;
                    652:         }
                    653:     }
                    654:     return -1;
                    655: }
1.468     raeburn   656: 
1.876     raeburn   657: function getDomainFromSelectbox(formname,udom) {
                    658:     var userdom;
                    659:     var formid = getFormIdByName(formname);
                    660:     if (formid > -1) {
                    661:         var domid = getIndexByName(formid,udom);
                    662:         if (domid > -1) {
                    663:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    665:             }
                    666:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    667:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   668:             }
                    669:         }
                    670:     }
1.876     raeburn   671:     return userdom;
                    672: }
                    673: 
                    674: ENDJS
1.468     raeburn   675: 
1.876     raeburn   676: }
                    677: 
1.1017    raeburn   678: sub javascript_array_indexof {
1.1018    raeburn   679:     return <<ENDJS;
1.1017    raeburn   680: <script type="text/javascript" language="JavaScript">
                    681: // <![CDATA[
                    682: 
                    683: if (!Array.prototype.indexOf) {
                    684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    685:         "use strict";
                    686:         if (this === void 0 || this === null) {
                    687:             throw new TypeError();
                    688:         }
                    689:         var t = Object(this);
                    690:         var len = t.length >>> 0;
                    691:         if (len === 0) {
                    692:             return -1;
                    693:         }
                    694:         var n = 0;
                    695:         if (arguments.length > 0) {
                    696:             n = Number(arguments[1]);
1.1088    foxr      697:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   698:                 n = 0;
                    699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    701:             }
                    702:         }
                    703:         if (n >= len) {
                    704:             return -1;
                    705:         }
                    706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    707:         for (; k < len; k++) {
                    708:             if (k in t && t[k] === searchElement) {
                    709:                 return k;
                    710:             }
                    711:         }
                    712:         return -1;
                    713:     }
                    714: }
                    715: 
                    716: // ]]>
                    717: </script>
                    718: 
                    719: ENDJS
                    720: 
                    721: }
                    722: 
1.876     raeburn   723: sub userbrowser_javascript {
                    724:     my $id_functions = &javascript_index_functions();
                    725:     return <<"ENDUSERBRW";
                    726: 
1.888     raeburn   727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   728:     var url = '/adm/pickuser?';
                    729:     var userdom = getDomainFromSelectbox(formname,udom);
                    730:     if (userdom != null) {
                    731:        if (userdom != '') {
                    732:            url += 'srchdom='+userdom+'&';
                    733:        }
                    734:     }
                    735:     url += 'form=' + formname + '&unameelement='+uname+
                    736:                                 '&udomelement='+udom+
                    737:                                 '&ulastelement='+ulast+
                    738:                                 '&ufirstelement='+ufirst+
                    739:                                 '&uemailelement='+uemail+
1.881     raeburn   740:                                 '&hideudomelement='+hideudom+
                    741:                                 '&coursedom='+crsdom;
1.888     raeburn   742:     if ((caller != null) && (caller != undefined)) {
                    743:         url += '&caller='+caller;
                    744:     }
1.876     raeburn   745:     var title = 'User_Browser';
                    746:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    747:     options += ',width=700,height=600';
                    748:     var stdeditbrowser = open(url,title,options,'1');
                    749:     stdeditbrowser.focus();
                    750: }
                    751: 
1.888     raeburn   752: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   753:     var formid = getFormIdByName(formname);
                    754:     if (formid > -1) {
1.888     raeburn   755:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   756:         var domid = getIndexByName(formid,udom);
                    757:         var hidedomid = getIndexByName(formid,origdom);
                    758:         if (hidedomid > -1) {
                    759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   760:             var unameval = document.forms[formid].elements[unameid].value;
                    761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    762:                 if (domid > -1) {
                    763:                     var slct = document.forms[formid].elements[domid];
                    764:                     if (slct.type == 'select-one') {
                    765:                         var i;
                    766:                         for (i=0;i<slct.length;i++) {
                    767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    768:                         }
                    769:                     }
                    770:                     if (slct.type == 'hidden') {
                    771:                         slct.value = fixeddom;
1.876     raeburn   772:                     }
                    773:                 }
1.468     raeburn   774:             }
                    775:         }
                    776:     }
1.876     raeburn   777:     return;
                    778: }
                    779: 
                    780: $id_functions
                    781: ENDUSERBRW
1.468     raeburn   782: }
                    783: 
                    784: sub setsec_javascript {
1.1116    raeburn   785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    787:         $communityrolestr);
                    788:     if ($role_element ne '') {
                    789:         my @allroles = ('st','ta','ep','in','ad');
                    790:         foreach my $crstype ('Course','Community') {
                    791:             if ($crstype eq 'Community') {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    796:             } else {
                    797:                 foreach my $role (@allroles) {
                    798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    799:                 }
                    800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    801:             }
                    802:         }
                    803:         $rolestr = '"'.join('","',@allroles).'"';
                    804:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    806:     }
1.468     raeburn   807:     my $setsections = qq|
                    808: function setSect(sectionlist) {
1.629     raeburn   809:     var sectionsArray = new Array();
                    810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    811:         sectionsArray = sectionlist.split(",");
                    812:     }
1.468     raeburn   813:     var numSections = sectionsArray.length;
                    814:     document.$formname.$sec_element.length = 0;
                    815:     if (numSections == 0) {
                    816:         document.$formname.$sec_element.multiple=false;
                    817:         document.$formname.$sec_element.size=1;
                    818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    819:     } else {
                    820:         if (numSections == 1) {
                    821:             document.$formname.$sec_element.multiple=false;
                    822:             document.$formname.$sec_element.size=1;
                    823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    826:         } else {
                    827:             for (var i=0; i<numSections; i++) {
                    828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    829:             }
                    830:             document.$formname.$sec_element.multiple=true
                    831:             if (numSections < 3) {
                    832:                 document.$formname.$sec_element.size=numSections;
                    833:             } else {
                    834:                 document.$formname.$sec_element.size=3;
                    835:             }
                    836:             document.$formname.$sec_element.options[0].selected = false
                    837:         }
                    838:     }
1.91      www       839: }
1.905     raeburn   840: 
                    841: function setRole(crstype) {
1.468     raeburn   842: |;
1.905     raeburn   843:     if ($role_element eq '') {
                    844:         $setsections .= '    return;
                    845: }
                    846: ';
                    847:     } else {
                    848:         $setsections .= qq|
                    849:     var elementLength = document.$formname.$role_element.length;
                    850:     var allroles = Array($rolestr);
                    851:     var courserolenames = Array($courserolestr);
                    852:     var communityrolenames = Array($communityrolestr);
                    853:     if (elementLength != undefined) {
                    854:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    855:             if (crstype == 'Course') {
                    856:                 return;
                    857:             } else {
                    858:                 allroles[5] = 'co';
                    859:                 for (var i=0; i<6; i++) {
                    860:                     document.$formname.$role_element.options[i].value = allroles[i];
                    861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    862:                 }
                    863:             }
                    864:         } else {
                    865:             if (crstype == 'Community') {
                    866:                 return;
                    867:             } else {
                    868:                 allroles[5] = 'cc';
                    869:                 for (var i=0; i<6; i++) {
                    870:                     document.$formname.$role_element.options[i].value = allroles[i];
                    871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    872:                 }
                    873:             }
                    874:         }
                    875:     }
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.1116    raeburn   880:     if ($credits_element) {
                    881:         $setsections .= qq|
                    882: function setCredits(defaultcredits) {
                    883:     document.$formname.$credits_element.value = defaultcredits;
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.468     raeburn   888:     return $setsections;
                    889: }
                    890: 
1.91      www       891: sub selectcourse_link {
1.909     raeburn   892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    893:        $typeelement) = @_;
                    894:    my $type = $selecttype;
1.871     raeburn   895:    my $linktext = &mt('Select Course');
                    896:    if ($selecttype eq 'Community') {
1.909     raeburn   897:        $linktext = &mt('Select Community');
1.1239    raeburn   898:    } elsif ($selecttype eq 'Placement') {
                    899:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   935:             if (!field[i].disabled) { 
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1093    raeburn   940:         if (!field.disabled) { 
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1256    raeburn   960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1256    raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1241    raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1241    raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1220    raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1015:                 push(@possibles,$id);
                   1016:             } 
1.687     raeburn  1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1256    raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1117    raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1117    raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.1088    foxr     1052: 
                   1053: =item * &list_languages()
                   1054: 
                   1055: Returns an array reference that is suitable for use in language prompters.
                   1056: Each array element is itself a two element array.  The first element
                   1057: is the language code.  The second element a descsriptiuon of the 
                   1058: language itself.  This is suitable for use in e.g.
                   1059: &Apache::edit::select_arg (once dereferenced that is).
                   1060: 
                   1061: =cut 
                   1062: 
                   1063: sub list_languages {
                   1064:     my @lang_choices;
                   1065: 
                   1066:     foreach my $id (&languageids()) {
                   1067: 	my $code = &supportedlanguagecode($id);
                   1068: 	if ($code) {
                   1069: 	    my $selector    = $supported_codes{$id};
                   1070: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1071: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1072: 	}
                   1073:     }
                   1074:     return \@lang_choices;
                   1075: }
                   1076: 
                   1077: =pod
                   1078: 
1.648     raeburn  1079: =item * &linked_select_forms(...)
1.36      matthew  1080: 
                   1081: linked_select_forms returns a string containing a <script></script> block
                   1082: and html for two <select> menus.  The select menus will be linked in that
                   1083: changing the value of the first menu will result in new values being placed
                   1084: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1085: order unless a defined order is provided.
1.36      matthew  1086: 
                   1087: linked_select_forms takes the following ordered inputs:
                   1088: 
                   1089: =over 4
                   1090: 
1.112     bowersj2 1091: =item * $formname, the name of the <form> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $firstdefault, the default value for the first menu
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1102: 
1.609     raeburn  1103: =item * $menuorder, the order of values in the first menu
                   1104: 
1.1115    raeburn  1105: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1106:         event for the first <select> tag
                   1107: 
                   1108: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1109:         event for the second <select> tag
                   1110: 
1.1245    raeburn  1111: =item * $suffix, to differentiate separate uses of select2data javascript
                   1112:         objects in a page.
                   1113: 
1.41      ng       1114: =back 
                   1115: 
1.36      matthew  1116: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1118: values for the first select menu.  The text that coincides with the 
1.41      ng       1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1120: and text for the second menu are given in the hash pointed to by 
                   1121: $menu{$choice1}->{'select2'}.  
                   1122: 
1.112     bowersj2 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1124:                        default => "B3",
                   1125:                        select2 => { 
                   1126:                            B1 => "Choice B1",
                   1127:                            B2 => "Choice B2",
                   1128:                            B3 => "Choice B3",
                   1129:                            B4 => "Choice B4"
1.609     raeburn  1130:                            },
                   1131:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1132:                    },
                   1133:                A2 => { text =>"Choice A2" ,
                   1134:                        default => "C2",
                   1135:                        select2 => { 
                   1136:                            C1 => "Choice C1",
                   1137:                            C2 => "Choice C2",
                   1138:                            C3 => "Choice C3"
1.609     raeburn  1139:                            },
                   1140:                        order => ['C2','C1','C3'],
1.112     bowersj2 1141:                    },
                   1142:                A3 => { text =>"Choice A3" ,
                   1143:                        default => "D6",
                   1144:                        select2 => { 
                   1145:                            D1 => "Choice D1",
                   1146:                            D2 => "Choice D2",
                   1147:                            D3 => "Choice D3",
                   1148:                            D4 => "Choice D4",
                   1149:                            D5 => "Choice D5",
                   1150:                            D6 => "Choice D6",
                   1151:                            D7 => "Choice D7"
1.609     raeburn  1152:                            },
                   1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1154:                    }
                   1155:                );
1.36      matthew  1156: 
                   1157: =cut
                   1158: 
                   1159: sub linked_select_forms {
                   1160:     my ($formname,
                   1161:         $middletext,
                   1162:         $firstdefault,
                   1163:         $firstselectname,
                   1164:         $secondselectname, 
1.609     raeburn  1165:         $hashref,
                   1166:         $menuorder,
1.1115    raeburn  1167:         $onchangefirst,
1.1245    raeburn  1168:         $onchangesecond,
                   1169:         $suffix
1.36      matthew  1170:         ) = @_;
                   1171:     my $second = "document.$formname.$secondselectname";
                   1172:     my $first = "document.$formname.$firstselectname";
                   1173:     # output the javascript to do the changing
                   1174:     my $result = '';
1.776     bisitz   1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1176:     $result.="// <![CDATA[\n";
1.1245    raeburn  1177:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1178:     $" = '","';
                   1179:     my $debug = '';
                   1180:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1183:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1187:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1188:         }
1.36      matthew  1189:         $result.="\"@s2values\");\n";
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1191:         my @s2texts;
                   1192:         foreach my $value (@s2values) {
1.1263    raeburn  1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1194:         }
                   1195:         $result.="\"@s2texts\");\n";
                   1196:     }
                   1197:     $"=' ';
                   1198:     $result.= <<"END";
                   1199: 
1.1245    raeburn  1200: function select1${suffix}_changed() {
1.36      matthew  1201:     // Determine new choice
1.1245    raeburn  1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1203:     // update select2
1.1245    raeburn  1204:     var values     = select2data${suffix}[newvalue].values;
                   1205:     var texts      = select2data${suffix}[newvalue].texts;
                   1206:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1207:     var i;
                   1208:     // out with the old
1.1245    raeburn  1209:     $second.options.length = 0;
                   1210:     // in with the new
1.36      matthew  1211:     for (i=0;i<values.length; i++) {
                   1212:         $second.options[i] = new Option(values[i]);
1.143     matthew  1213:         $second.options[i].value = values[i];
1.36      matthew  1214:         $second.options[i].text = texts[i];
                   1215:         if (values[i] == select2def) {
                   1216:             $second.options[i].selected = true;
                   1217:         }
                   1218:     }
                   1219: }
1.824     bisitz   1220: // ]]>
1.36      matthew  1221: </script>
                   1222: END
                   1223:     # output the initial values for the selection lists
1.1245    raeburn  1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1225:     my @order = sort(keys(%{$hashref}));
                   1226:     if (ref($menuorder) eq 'ARRAY') {
                   1227:         @order = @{$menuorder};
                   1228:     }
                   1229:     foreach my $value (@order) {
1.36      matthew  1230:         $result.="    <option value=\"$value\" ";
1.253     albertel 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1233:     }
                   1234:     $result .= "</select>\n";
                   1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1236:     $result .= $middletext;
1.1115    raeburn  1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1238:     if ($onchangesecond) {
                   1239:         $result .= ' onchange="'.$onchangesecond.'"';
                   1240:     }
                   1241:     $result .= ">\n";
1.36      matthew  1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1243:     
                   1244:     my @secondorder = sort(keys(%select2));
                   1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1247:     }
                   1248:     foreach my $value (@secondorder) {
1.36      matthew  1249:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1251:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1252:     }
                   1253:     $result .= "</select>\n";
                   1254:     #    return $debug;
                   1255:     return $result;
                   1256: }   #  end of sub linked_select_forms {
                   1257: 
1.45      matthew  1258: =pod
1.44      bowersj2 1259: 
1.973     raeburn  1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1261: 
1.112     bowersj2 1262: Returns a string corresponding to an HTML link to the given help
                   1263: $topic, where $topic corresponds to the name of a .tex file in
                   1264: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1265: spaces. 
                   1266: 
                   1267: $text will optionally be linked to the same topic, allowing you to
                   1268: link text in addition to the graphic. If you do not want to link
                   1269: text, but wish to specify one of the later parameters, pass an
                   1270: empty string. 
                   1271: 
                   1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1273: the link will not open a new window. If false, the link will open
                   1274: a new window using Javascript. (Default is false.) 
                   1275: 
                   1276: $width and $height are optional numerical parameters that will
                   1277: override the width and height of the popped up window, which may
1.973     raeburn  1278: be useful for certain help topics with big pictures included.
                   1279: 
                   1280: $imgid is the id of the img tag used for the help icon. This may be
                   1281: used in a javascript call to switch the image src.  See 
                   1282: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1283: 
                   1284: =cut
                   1285: 
                   1286: sub help_open_topic {
1.973     raeburn  1287:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1288:     $text = "" if (not defined $text);
1.44      bowersj2 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1290:     $width = 500 if (not defined $width);
1.44      bowersj2 1291:     $height = 400 if (not defined $height);
                   1292:     my $filename = $topic;
                   1293:     $filename =~ s/ /_/g;
                   1294: 
1.48      bowersj2 1295:     my $template = "";
                   1296:     my $link;
1.572     banghart 1297:     
1.159     www      1298:     $topic=~s/\W/\_/g;
1.44      bowersj2 1299: 
1.572     banghart 1300:     if (!$stayOnPage) {
1.1033    www      1301: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1302:     } elsif ($stayOnPage eq 'popup') {
                   1303:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1304:     } else {
1.48      bowersj2 1305: 	$link = "/adm/help/${filename}.hlp";
                   1306:     }
                   1307: 
                   1308:     # Add the text
1.1314    raeburn  1309:     my $target = ' target="_top"';
                   1310:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1311:         $target = '';
                   1312:     }
1.755     neumanie 1313:     if ($text ne "") {	
1.763     bisitz   1314: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1315:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1316:                   .$text.'</a>';
1.48      bowersj2 1317:     }
                   1318: 
1.763     bisitz   1319:     # (Always) Add the graphic
1.179     matthew  1320:     my $title = &mt('Online Help');
1.667     raeburn  1321:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1322:     if ($imgid ne '') {
                   1323:         $imgid = ' id="'.$imgid.'"';
                   1324:     }
1.1314    raeburn  1325:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1326:               .'<img src="'.$helpicon.'" border="0"'
                   1327:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1328:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1329:               .' /></a>';
                   1330:     if ($text ne "") {	
                   1331:         $template.='</span>';
                   1332:     }
1.44      bowersj2 1333:     return $template;
                   1334: 
1.106     bowersj2 1335: }
                   1336: 
                   1337: # This is a quicky function for Latex cheatsheet editing, since it 
                   1338: # appears in at least four places
                   1339: sub helpLatexCheatsheet {
1.1037    www      1340:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1341:     my $out;
1.106     bowersj2 1342:     my $addOther = '';
1.732     raeburn  1343:     if ($topic) {
1.1037    www      1344: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1345:     }
                   1346:     $out = '<span>' # Start cheatsheet
                   1347: 	  .$addOther
                   1348:           .'<span>'
1.1037    www      1349: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1350: 	  .'</span> <span>'
1.1037    www      1351: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1352: 	  .'</span>';
1.732     raeburn  1353:     unless ($not_author) {
1.1186    kruse    1354:         $out .= '<span>'
                   1355:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1356:                .'</span> <span>'
                   1357:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1358: 	       .'</span>';
1.732     raeburn  1359:     }
1.763     bisitz   1360:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1361:     return $out;
1.172     www      1362: }
                   1363: 
1.430     albertel 1364: sub general_help {
                   1365:     my $helptopic='Student_Intro';
                   1366:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1367: 	$helptopic='Authoring_Intro';
1.907     raeburn  1368:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1369: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1370:     } elsif ($env{'request.role'}=~/^dc/) {
                   1371:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1372:     }
                   1373:     return $helptopic;
                   1374: }
                   1375: 
                   1376: sub update_help_link {
                   1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1378:     my $origurl = $ENV{'REQUEST_URI'};
                   1379:     $origurl=~s|^/~|/priv/|;
                   1380:     my $timestamp = time;
                   1381:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1382:         $$datum = &escape($$datum);
                   1383:     }
                   1384: 
                   1385:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1386:     my $output .= <<"ENDOUTPUT";
                   1387: <script type="text/javascript">
1.824     bisitz   1388: // <![CDATA[
1.430     albertel 1389: banner_link = '$banner_link';
1.824     bisitz   1390: // ]]>
1.430     albertel 1391: </script>
                   1392: ENDOUTPUT
                   1393:     return $output;
                   1394: }
                   1395: 
                   1396: # now just updates the help link and generates a blue icon
1.193     raeburn  1397: sub help_open_menu {
1.430     albertel 1398:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1399: 	= @_;    
1.949     droeschl 1400:     $stayOnPage = 1;
1.430     albertel 1401:     my $output;
                   1402:     if ($component_help) {
                   1403: 	if (!$text) {
                   1404: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1405: 				       $width,$height);
                   1406: 	} else {
                   1407: 	    my $help_text;
                   1408: 	    $help_text=&unescape($topic);
                   1409: 	    $output='<table><tr><td>'.
                   1410: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1411: 				 $width,$height).'</td></tr></table>';
                   1412: 	}
                   1413:     }
                   1414:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1415:     return $output.$banner_link;
                   1416: }
                   1417: 
                   1418: sub top_nav_help {
                   1419:     my ($text) = @_;
1.436     albertel 1420:     $text = &mt($text);
1.949     droeschl 1421:     my $stay_on_page = 1;
                   1422: 
1.1168    raeburn  1423:     my ($link,$banner_link);
                   1424:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1425:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1426: 	                         : "javascript:helpMenu('open')";
                   1427:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1428:     }
1.201     raeburn  1429:     my $title = &mt('Get help');
1.1168    raeburn  1430:     if ($link) {
                   1431:         return <<"END";
1.436     albertel 1432: $banner_link
1.1159    raeburn  1433: <a href="$link" title="$title">$text</a>
1.436     albertel 1434: END
1.1168    raeburn  1435:     } else {
                   1436:         return '&nbsp;'.$text.'&nbsp;';
                   1437:     }
1.436     albertel 1438: }
                   1439: 
                   1440: sub help_menu_js {
1.1154    raeburn  1441:     my ($httphost) = @_;
1.949     droeschl 1442:     my $stayOnPage = 1;
1.436     albertel 1443:     my $width = 620;
                   1444:     my $height = 600;
1.430     albertel 1445:     my $helptopic=&general_help();
1.1154    raeburn  1446:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1447:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1448:     my $start_page =
                   1449:         &Apache::loncommon::start_page('Help Menu', undef,
                   1450: 				       {'frameset'    => 1,
                   1451: 					'js_ready'    => 1,
1.1154    raeburn  1452:                                         'use_absolute' => $httphost,
1.331     albertel 1453: 					'add_entries' => {
1.1168    raeburn  1454: 					    'border' => '0', 
1.579     raeburn  1455: 					    'rows'   => "110,*",},});
1.331     albertel 1456:     my $end_page =
                   1457:         &Apache::loncommon::end_page({'frameset' => 1,
                   1458: 				      'js_ready' => 1,});
                   1459: 
1.436     albertel 1460:     my $template .= <<"ENDTEMPLATE";
                   1461: <script type="text/javascript">
1.877     bisitz   1462: // <![CDATA[
1.253     albertel 1463: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1464: var banner_link = '';
1.243     raeburn  1465: function helpMenu(target) {
                   1466:     var caller = this;
                   1467:     if (target == 'open') {
                   1468:         var newWindow = null;
                   1469:         try {
1.262     albertel 1470:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1471:         }
                   1472:         catch(error) {
                   1473:             writeHelp(caller);
                   1474:             return;
                   1475:         }
                   1476:         if (newWindow) {
                   1477:             caller = newWindow;
                   1478:         }
1.193     raeburn  1479:     }
1.243     raeburn  1480:     writeHelp(caller);
                   1481:     return;
                   1482: }
                   1483: function writeHelp(caller) {
1.1168    raeburn  1484:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1485:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1486:     caller.document.close();
                   1487:     caller.focus();
1.193     raeburn  1488: }
1.877     bisitz   1489: // END LON-CAPA Internal -->
1.253     albertel 1490: // ]]>
1.436     albertel 1491: </script>
1.193     raeburn  1492: ENDTEMPLATE
                   1493:     return $template;
                   1494: }
                   1495: 
1.172     www      1496: sub help_open_bug {
                   1497:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1498:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1499:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1500:     $text = "" if (not defined $text);
                   1501: 	$stayOnPage=1;
1.184     albertel 1502:     $width = 600 if (not defined $width);
                   1503:     $height = 600 if (not defined $height);
1.172     www      1504: 
                   1505:     $topic=~s/\W+/\+/g;
                   1506:     my $link='';
                   1507:     my $template='';
1.379     albertel 1508:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1509: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1510:     if (!$stayOnPage)
                   1511:     {
                   1512: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1513:     }
                   1514:     else
                   1515:     {
                   1516: 	$link = $url;
                   1517:     }
1.1314    raeburn  1518: 
                   1519:     my $target = ' target="_top"';
                   1520:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1521:         $target = '';
                   1522:     }
1.172     www      1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
                   1527:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1528:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('Report a Bug');
1.215     albertel 1533:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1535:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
                   1540: }
                   1541: 
                   1542: sub help_open_faq {
                   1543:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1544:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1545:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1546:     $text = "" if (not defined $text);
                   1547: 	$stayOnPage=1;
                   1548:     $width = 350 if (not defined $width);
                   1549:     $height = 400 if (not defined $height);
                   1550: 
                   1551:     $topic=~s/\W+/\+/g;
                   1552:     my $link='';
                   1553:     my $template='';
                   1554:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1555:     if (!$stayOnPage)
                   1556:     {
                   1557: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1558:     }
                   1559:     else
                   1560:     {
                   1561: 	$link = $url;
                   1562:     }
                   1563: 
                   1564:     # Add the text
                   1565:     if ($text ne "")
                   1566:     {
                   1567: 	$template .= 
1.173     www      1568:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1569:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1570:     }
                   1571: 
                   1572:     # Add the graphic
1.179     matthew  1573:     my $title = &mt('View the FAQ');
1.215     albertel 1574:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1575:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1576:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1577: ENDTEMPLATE
                   1578:     if ($text ne '') { $template.='</td></tr></table>' };
                   1579:     return $template;
                   1580: 
1.44      bowersj2 1581: }
1.37      matthew  1582: 
1.180     matthew  1583: ###############################################################
                   1584: ###############################################################
                   1585: 
1.45      matthew  1586: =pod
                   1587: 
1.648     raeburn  1588: =item * &change_content_javascript():
1.256     matthew  1589: 
                   1590: This and the next function allow you to create small sections of an
                   1591: otherwise static HTML page that you can update on the fly with
                   1592: Javascript, even in Netscape 4.
                   1593: 
                   1594: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1595: must be written to the HTML page once. It will prove the Javascript
                   1596: function "change(name, content)". Calling the change function with the
                   1597: name of the section 
                   1598: you want to update, matching the name passed to C<changable_area>, and
                   1599: the new content you want to put in there, will put the content into
                   1600: that area.
                   1601: 
                   1602: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1603: to contain room for the original contents. You need to "make space"
                   1604: for whatever changes you wish to make, and be B<sure> to check your
                   1605: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1606: it's adequate for updating a one-line status display, but little more.
                   1607: This script will set the space to 100% width, so you only need to
                   1608: worry about height in Netscape 4.
                   1609: 
                   1610: Modern browsers are much less limiting, and if you can commit to the
                   1611: user not using Netscape 4, this feature may be used freely with
                   1612: pretty much any HTML.
                   1613: 
                   1614: =cut
                   1615: 
                   1616: sub change_content_javascript {
                   1617:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1618:     if ($env{'browser.type'} eq 'netscape' &&
                   1619: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1620: 	return (<<NETSCAPE4);
                   1621: 	function change(name, content) {
                   1622: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1623: 	    doc.open();
                   1624: 	    doc.write(content);
                   1625: 	    doc.close();
                   1626: 	}
                   1627: NETSCAPE4
                   1628:     } else {
                   1629: 	# Otherwise, we need to use semi-standards-compliant code
                   1630: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1631: 	# is really scary, and every useful browser supports it
                   1632: 	return (<<DOMBASED);
                   1633: 	function change(name, content) {
                   1634: 	    element = document.getElementById(name);
                   1635: 	    element.innerHTML = content;
                   1636: 	}
                   1637: DOMBASED
                   1638:     }
                   1639: }
                   1640: 
                   1641: =pod
                   1642: 
1.648     raeburn  1643: =item * &changable_area($name,$origContent):
1.256     matthew  1644: 
                   1645: This provides a "changable area" that can be modified on the fly via
                   1646: the Javascript code provided in C<change_content_javascript>. $name is
                   1647: the name you will use to reference the area later; do not repeat the
                   1648: same name on a given HTML page more then once. $origContent is what
                   1649: the area will originally contain, which can be left blank.
                   1650: 
                   1651: =cut
                   1652: 
                   1653: sub changable_area {
                   1654:     my ($name, $origContent) = @_;
                   1655: 
1.258     albertel 1656:     if ($env{'browser.type'} eq 'netscape' &&
                   1657: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1658: 	# If this is netscape 4, we need to use the Layer tag
                   1659: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1660:     } else {
                   1661: 	return "<span id='$name'>$origContent</span>";
                   1662:     }
                   1663: }
                   1664: 
                   1665: =pod
                   1666: 
1.648     raeburn  1667: =item * &viewport_geometry_js 
1.590     raeburn  1668: 
                   1669: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: 
                   1674: sub viewport_geometry_js { 
                   1675:     return <<"GEOMETRY";
                   1676: var Geometry = {};
                   1677: function init_geometry() {
                   1678:     if (Geometry.init) { return };
                   1679:     Geometry.init=1;
                   1680:     if (window.innerHeight) {
                   1681:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1682:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1683:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1684:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1685:     }
                   1686:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1687:         Geometry.getViewportHeight =
                   1688:             function() { return document.documentElement.clientHeight; };
                   1689:         Geometry.getViewportWidth =
                   1690:             function() { return document.documentElement.clientWidth; };
                   1691: 
                   1692:         Geometry.getHorizontalScroll =
                   1693:             function() { return document.documentElement.scrollLeft; };
                   1694:         Geometry.getVerticalScroll =
                   1695:             function() { return document.documentElement.scrollTop; };
                   1696:     }
                   1697:     else if (document.body.clientHeight) {
                   1698:         Geometry.getViewportHeight =
                   1699:             function() { return document.body.clientHeight; };
                   1700:         Geometry.getViewportWidth =
                   1701:             function() { return document.body.clientWidth; };
                   1702:         Geometry.getHorizontalScroll =
                   1703:             function() { return document.body.scrollLeft; };
                   1704:         Geometry.getVerticalScroll =
                   1705:             function() { return document.body.scrollTop; };
                   1706:     }
                   1707: }
                   1708: 
                   1709: GEOMETRY
                   1710: }
                   1711: 
                   1712: =pod
                   1713: 
1.648     raeburn  1714: =item * &viewport_size_js()
1.590     raeburn  1715: 
                   1716: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1717: 
                   1718: =cut
                   1719: 
                   1720: sub viewport_size_js {
                   1721:     my $geometry = &viewport_geometry_js();
                   1722:     return <<"DIMS";
                   1723: 
                   1724: $geometry
                   1725: 
                   1726: function getViewportDims(width,height) {
                   1727:     init_geometry();
                   1728:     width.value = Geometry.getViewportWidth();
                   1729:     height.value = Geometry.getViewportHeight();
                   1730:     return;
                   1731: }
                   1732: 
                   1733: DIMS
                   1734: }
                   1735: 
                   1736: =pod
                   1737: 
1.648     raeburn  1738: =item * &resize_textarea_js()
1.565     albertel 1739: 
                   1740: emits the needed javascript to resize a textarea to be as big as possible
                   1741: 
                   1742: creates a function resize_textrea that takes two IDs first should be
                   1743: the id of the element to resize, second should be the id of a div that
                   1744: surrounds everything that comes after the textarea, this routine needs
                   1745: to be attached to the <body> for the onload and onresize events.
                   1746: 
1.648     raeburn  1747: =back
1.565     albertel 1748: 
                   1749: =cut
                   1750: 
                   1751: sub resize_textarea_js {
1.590     raeburn  1752:     my $geometry = &viewport_geometry_js();
1.565     albertel 1753:     return <<"RESIZE";
                   1754:     <script type="text/javascript">
1.824     bisitz   1755: // <![CDATA[
1.590     raeburn  1756: $geometry
1.565     albertel 1757: 
1.588     albertel 1758: function getX(element) {
                   1759:     var x = 0;
                   1760:     while (element) {
                   1761: 	x += element.offsetLeft;
                   1762: 	element = element.offsetParent;
                   1763:     }
                   1764:     return x;
                   1765: }
                   1766: function getY(element) {
                   1767:     var y = 0;
                   1768:     while (element) {
                   1769: 	y += element.offsetTop;
                   1770: 	element = element.offsetParent;
                   1771:     }
                   1772:     return y;
                   1773: }
                   1774: 
                   1775: 
1.565     albertel 1776: function resize_textarea(textarea_id,bottom_id) {
                   1777:     init_geometry();
                   1778:     var textarea        = document.getElementById(textarea_id);
                   1779:     //alert(textarea);
                   1780: 
1.588     albertel 1781:     var textarea_top    = getY(textarea);
1.565     albertel 1782:     var textarea_height = textarea.offsetHeight;
                   1783:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1784:     var bottom_top      = getY(bottom);
1.565     albertel 1785:     var bottom_height   = bottom.offsetHeight;
                   1786:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1787:     var fudge           = 23;
1.565     albertel 1788:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1789:     if (new_height < 300) {
                   1790: 	new_height = 300;
                   1791:     }
                   1792:     textarea.style.height=new_height+'px';
                   1793: }
1.824     bisitz   1794: // ]]>
1.565     albertel 1795: </script>
                   1796: RESIZE
                   1797: 
                   1798: }
                   1799: 
1.1205    golterma 1800: sub colorfuleditor_js {
1.1248    raeburn  1801:     my $browse_or_search;
                   1802:     my $respath;
                   1803:     my ($cnum,$cdom) = &crsauthor_url();
                   1804:     if ($cnum) {
                   1805:         $respath = "/res/$cdom/$cnum/";
                   1806:         my %js_lt = &Apache::lonlocal::texthash(
                   1807:             sunm => 'Sub-directory name',
                   1808:             save => 'Save page to make this permanent',
                   1809:         );
                   1810:         &js_escape(\%js_lt);
                   1811:         $browse_or_search = <<"END";
                   1812: 
                   1813:     function toggleChooser(form,element,titleid,only,search) {
                   1814:         var disp = 'none';
                   1815:         if (document.getElementById('chooser_'+element)) {
                   1816:             var curr = document.getElementById('chooser_'+element).style.display;
                   1817:             if (curr == 'none') {
                   1818:                 disp='inline';
                   1819:                 if (form.elements['chooser_'+element].length) {
                   1820:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1821:                         form.elements['chooser_'+element][i].checked = false;
                   1822:                     }
                   1823:                 }
                   1824:                 toggleResImport(form,element);
                   1825:             }
                   1826:             document.getElementById('chooser_'+element).style.display = disp;
                   1827:         }
                   1828:     }
                   1829: 
                   1830:     function toggleCrsFile(form,element,numdirs) {
                   1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1832:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1833:             if (curr == 'none') {
                   1834:                 if (numdirs) {
                   1835:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1836:                     if (numdirs > 1) {
                   1837:                         window['select1'+element+'_changed']();
                   1838:                     }
                   1839:                 }
                   1840:             } 
                   1841:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1842:             
                   1843:         }
                   1844:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1845:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1846:             if (document.getElementById('uploadcrsres_'+element)) {
                   1847:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1848:             }
                   1849:         }
                   1850:         return;
                   1851:     }
                   1852: 
                   1853:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1854:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1855:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1856:         }
                   1857:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1858:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1859:             if (curr == 'none') {
                   1860:                 if (numcrsdirs) {
                   1861:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1862:                    form.elements['newsubdir_'+element][0].checked = true;
                   1863:                    toggleNewsubdir(form,element);
                   1864:                 }
                   1865:             }
                   1866:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1867:         }
                   1868:         return;
                   1869:     }
                   1870: 
                   1871:     function toggleResImport(form,element) {
                   1872:         var choices = new Array('crsres','upload');
                   1873:         for (var i=0; i<choices.length; i++) {
                   1874:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1875:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1876:             }
                   1877:         }
                   1878:     }
                   1879: 
                   1880:     function toggleNewsubdir(form,element) {
                   1881:         var newsub = form.elements['newsubdir_'+element];
                   1882:         if (newsub) {
                   1883:             if (newsub.length) {
                   1884:                 for (var j=0; j<newsub.length; j++) {
                   1885:                     if (newsub[j].checked) {
                   1886:                         if (document.getElementById('newsubdirname_'+element)) {
                   1887:                             if (newsub[j].value == '1') {
                   1888:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1889:                                 if (document.getElementById('newsubdir_'+element)) {
                   1890:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1891:                                 }
                   1892:                             } else {
                   1893:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1894:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1895:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1896:                             }
                   1897:                         }
                   1898:                         break; 
                   1899:                     }
                   1900:                 }
                   1901:             }
                   1902:         }
                   1903:     }
                   1904: 
                   1905:     function updateCrsFile(form,element) {
                   1906:         var directory = form.elements['coursepath_'+element];
                   1907:         var filename = form.elements['coursefile_'+element];
                   1908:         var path = directory.options[directory.selectedIndex].value;
                   1909:         var file = filename.options[filename.selectedIndex].value;
                   1910:         form.elements[element].value = '$respath';
                   1911:         if (path == '/') {
                   1912:             form.elements[element].value += file;
                   1913:         } else {
                   1914:             form.elements[element].value += path+'/'+file;
                   1915:         }
                   1916:         unClean();
                   1917:         if (document.getElementById('previewimg_'+element)) {
                   1918:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1919:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1920:         }
                   1921:         if (document.getElementById('showimg_'+element)) {
                   1922:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1923:         }
                   1924:         toggleChooser(form,element);
                   1925:         return;
                   1926:     }
                   1927: 
                   1928:     function uploadDone(suffix,name) {
                   1929:         if (name) {
                   1930: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1931:             unClean();
                   1932:             toggleChooser(document.forms["lonhomework"],suffix);
                   1933:         }
                   1934:     }
                   1935: 
                   1936: \$(document).ready(function(){
                   1937: 
                   1938:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1939:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1940:             var buttonId = this.id;
                   1941:             var suffix = buttonId.toString();
                   1942:             suffix = suffix.replace(/^crsupload_/,'');
                   1943:             event.preventDefault();
                   1944:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1945:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1946:             \$(this.form).submit();
                   1947:             document.lonhomework.target = '';
                   1948:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1949:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1950:             }
                   1951:             return false;
                   1952:         }
                   1953:     });
                   1954: });
                   1955: END
                   1956:     }
1.1205    golterma 1957:     return <<"COLORFULEDIT"
                   1958: <script type="text/javascript">
                   1959: // <![CDATA[>
                   1960:     function fold_box(curDepth, lastresource){
                   1961: 
                   1962:     // we need a list because there can be several blocks you need to fold in one tag
                   1963:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1964:     // but there is only one folding button per tag
                   1965:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1966: 
                   1967:         if(block.item(0).style.display == 'none'){
                   1968: 
                   1969:             foldbutton.value = '@{[&mt("Hide")]}';
                   1970:             for (i = 0; i < block.length; i++){
                   1971:                 block.item(i).style.display = '';
                   1972:             }
                   1973:         }else{
                   1974: 
                   1975:             foldbutton.value = '@{[&mt("Show")]}';
                   1976:             for (i = 0; i < block.length; i++){
                   1977:                 // block.item(i).style.visibility = 'collapse';
                   1978:                 block.item(i).style.display = 'none';
                   1979:             }
                   1980:         };
                   1981:         saveState(lastresource);
                   1982:     }
                   1983: 
                   1984:     function saveState (lastresource) {
                   1985: 
                   1986:         var tag_list = getTagList();
                   1987:         if(tag_list != null){
                   1988:             var timestamp = new Date().getTime();
                   1989:             var key = lastresource;
                   1990: 
                   1991:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1992:             // starting with timestamp
                   1993:             var value = timestamp+';';
                   1994: 
                   1995:             // building the list of key-value pairs
                   1996:             for(var i = 0; i < tag_list.length; i++){
                   1997:                 value += tag_list[i]+',';
                   1998:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1999:             }
                   2000: 
                   2001:             // only iterate whole storage if nothing to override
                   2002:             if(localStorage.getItem(key) == null){        
                   2003: 
                   2004:                 // prevent storage from growing large
                   2005:                 if(localStorage.length > 50){
                   2006:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2007:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2008:                     var oldest_key;
                   2009:                     
                   2010:                     for(var i = 1; i < localStorage.length; i++){
                   2011:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2012:                             oldest_key = localStorage.key(i);
                   2013:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2014:                         }
                   2015:                     }
                   2016:                     localStorage.removeItem(oldest_key);
                   2017:                 }
                   2018:             }
                   2019:             localStorage.setItem(key,value);
                   2020:         }
                   2021:     }
                   2022: 
                   2023:     // restore folding status of blocks (on page load)
                   2024:     function restoreState (lastresource) {
                   2025:         if(localStorage.getItem(lastresource) != null){
                   2026:             var key = lastresource;
                   2027:             var value = localStorage.getItem(key);
                   2028:             var regex_delTimestamp = /^\d+;/;
                   2029: 
                   2030:             value.replace(regex_delTimestamp, '');
                   2031: 
                   2032:             var valueArr = value.split(';');
                   2033:             var pairs;
                   2034:             var elements;
                   2035:             for (var i = 0; i < valueArr.length; i++){
                   2036:                 pairs = valueArr[i].split(',');
                   2037:                 elements = document.getElementsByName(pairs[0]);
                   2038: 
                   2039:                 for (var j = 0; j < elements.length; j++){  
                   2040:                     elements[j].style.display = pairs[1];
                   2041:                     if (pairs[1] == "none"){
                   2042:                         var regex_id = /([_\\d]+)\$/;
                   2043:                         regex_id.exec(pairs[0]);
                   2044:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2045:                     }
                   2046:                 }
                   2047:             }
                   2048:         }
                   2049:     }
                   2050: 
                   2051:     function getTagList () {
                   2052:         
                   2053:         var stringToSearch = document.lonhomework.innerHTML;
                   2054: 
                   2055:         var ret = new Array();
                   2056:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2057:         var tag_list = stringToSearch.match(regex_findBlock);
                   2058: 
                   2059:         if(tag_list != null){
                   2060:             for(var i = 0; i < tag_list.length; i++){            
                   2061:                 ret.push(tag_list[i].replace(/"/, ''));
                   2062:             }
                   2063:         }
                   2064:         return ret;
                   2065:     }
                   2066: 
                   2067:     function saveScrollPosition (resource) {
                   2068:         var tag_list = getTagList();
                   2069: 
                   2070:         // we dont always want to jump to the first block
                   2071:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2072:         if(\$(window).scrollTop() > 170){
                   2073:             if(tag_list != null){
                   2074:                 var result;
                   2075:                 for(var i = 0; i < tag_list.length; i++){
                   2076:                     if(isElementInViewport(tag_list[i])){
                   2077:                         result += tag_list[i]+';';
                   2078:                     }
                   2079:                 }
                   2080:                 sessionStorage.setItem('anchor_'+resource, result);
                   2081:             }
                   2082:         } else {
                   2083:             // we dont need to save zero, just delete the item to leave everything tidy
                   2084:             sessionStorage.removeItem('anchor_'+resource);
                   2085:         }
                   2086:     }
                   2087: 
                   2088:     function restoreScrollPosition(resource){
                   2089: 
                   2090:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2091:         if(elem != null){
                   2092:             var tag_list = elem.split(';');
                   2093:             var elem_list;
                   2094: 
                   2095:             for(var i = 0; i < tag_list.length; i++){
                   2096:                 elem_list = document.getElementsByName(tag_list[i]);
                   2097:                 
                   2098:                 if(elem_list.length > 0){
                   2099:                     elem = elem_list[0];
                   2100:                     break;
                   2101:                 }
                   2102:             }
                   2103:             elem.scrollIntoView();
                   2104:         }
                   2105:     }
                   2106: 
                   2107:     function isElementInViewport(el) {
                   2108: 
                   2109:         // change to last element instead of first
                   2110:         var elem = document.getElementsByName(el);
                   2111:         var rect = elem[0].getBoundingClientRect();
                   2112: 
                   2113:         return (
                   2114:             rect.top >= 0 &&
                   2115:             rect.left >= 0 &&
                   2116:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2117:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2118:         );
                   2119:     }
                   2120:     
                   2121:     function autosize(depth){
                   2122:         var cmInst = window['cm'+depth];
                   2123:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2124: 
                   2125:         // is fixed size, switching to dynamic
                   2126:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2127:             cmInst.setSize("","auto");
                   2128:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2129:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2130: 
                   2131:         // is dynamic size, switching to fixed
                   2132:         } else {
                   2133:             cmInst.setSize("","300px");
                   2134:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2135:             sessionStorage.removeItem("autosized_"+depth);
                   2136:         }
                   2137:     }
                   2138: 
1.1248    raeburn  2139: $browse_or_search
1.1205    golterma 2140: 
                   2141: // ]]>
                   2142: </script>
                   2143: COLORFULEDIT
                   2144: }
                   2145: 
                   2146: sub xmleditor_js {
                   2147:     return <<XMLEDIT
                   2148: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2149: <script type="text/javascript">
                   2150: // <![CDATA[>
                   2151: 
                   2152:     function saveScrollPosition (resource) {
                   2153: 
                   2154:         var scrollPos = \$(window).scrollTop();
                   2155:         sessionStorage.setItem(resource,scrollPos);
                   2156:     }
                   2157: 
                   2158:     function restoreScrollPosition(resource){
                   2159: 
                   2160:         var scrollPos = sessionStorage.getItem(resource);
                   2161:         \$(window).scrollTop(scrollPos);
                   2162:     }
                   2163: 
                   2164:     // unless internet explorer
                   2165:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2166: 
                   2167:         \$(document).ready(function() {
                   2168:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2169:         });
                   2170:     }
                   2171: 
                   2172:     // inserts text at cursor position into codemirror (xml editor only)
                   2173:     function insertText(text){
                   2174:         cm.focus();
                   2175:         var curPos = cm.getCursor();
                   2176:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2177:     }
                   2178: // ]]>
                   2179: </script>
                   2180: XMLEDIT
                   2181: }
                   2182: 
                   2183: sub insert_folding_button {
                   2184:     my $curDepth = $Apache::lonxml::curdepth;
                   2185:     my $lastresource = $env{'request.ambiguous'};
                   2186: 
                   2187:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2188:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2189: }
                   2190: 
1.1248    raeburn  2191: sub crsauthor_url {
                   2192:     my ($url) = @_;
                   2193:     if ($url eq '') {
                   2194:         $url = $ENV{'REQUEST_URI'};
                   2195:     }
                   2196:     my ($cnum,$cdom);
                   2197:     if ($env{'request.course.id'}) {
                   2198:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2199:         if ($audom ne '' && $auname ne '') {
                   2200:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2201:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2202:                 $cnum = $auname;
                   2203:                 $cdom = $audom;
                   2204:             }
                   2205:         }
                   2206:     }
                   2207:     return ($cnum,$cdom);
                   2208: }
                   2209: 
                   2210: sub import_crsauthor_form {
1.1265    raeburn  2211:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2212:     return (0) unless ($env{'request.course.id'});
                   2213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2215:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2216:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2217:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2218:     my @ids=&Apache::lonnet::current_machine_ids();
                   2219:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2220:     
                   2221:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2222:         $is_home = 1;
                   2223:     }
                   2224:     $relpath = "/priv/$cdom/$cnum";
                   2225:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2226:     my %lt = &Apache::lonlocal::texthash (
                   2227:         fnam => 'Filename',
                   2228:         dire => 'Directory',
                   2229:     );
                   2230:     my $numdirs = scalar(keys(%files));
                   2231:     my (%possexts,$singledir,@singledirfiles);
                   2232:     if ($only) {
                   2233:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2234:     }
                   2235:     my (%nonemptydirs,$possdirs);
                   2236:     if ($numdirs > 1) {
                   2237:         my @order;
                   2238:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2239:             if (ref($files{$key}) eq 'HASH') {
                   2240:                 my $shown = $key;
                   2241:                 if ($key eq '') {
                   2242:                     $shown = '/';
                   2243:                 }
                   2244:                 my @ordered = ();
                   2245:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2246:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2247:                     if ($only) {
                   2248:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2249:                         unless ($possexts{lc($ext)}) {
                   2250:                             next;
                   2251:                         }
                   2252:                     }
                   2253:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2254:                     push(@ordered,$file);
                   2255:                 }
                   2256:                 if (@ordered) {
                   2257:                     push(@order,$key);
                   2258:                     $nonemptydirs{$key} = 1;
                   2259:                     $selimport_menus{$key}->{'text'} = $shown;
                   2260:                     $selimport_menus{$key}->{'default'} = '';
                   2261:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2262:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2263:                 }
                   2264:             }
                   2265:         }
                   2266:         $possdirs = scalar(keys(%nonemptydirs));
                   2267:         if ($possdirs > 1) {
                   2268:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2269:             $output = $lt{'dire'}.
                   2270:                       &linked_select_forms($form,'<br />'.
                   2271:                                            $lt{'fnam'},'',
                   2272:                                            $firstselectname,$secondselectname,
                   2273:                                            \%selimport_menus,\@order,
                   2274:                                            $onchangefirst,'',$suffix).'<br />';
                   2275:         } elsif ($possdirs == 1) {
                   2276:             $singledir = (keys(%nonemptydirs))[0];
                   2277:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2278:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2279:             }
                   2280:             delete($selimport_menus{$singledir});
                   2281:         }
                   2282:     } elsif ($numdirs == 1) {
                   2283:         $singledir = (keys(%files))[0];
                   2284:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2285:             if ($only) {
                   2286:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2287:                 unless ($possexts{lc($ext)}) {
                   2288:                     next;
                   2289:                 }
1.1315    raeburn  2290:             } else {
                   2291:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2292:             }
                   2293:             push(@singledirfiles,$file);
                   2294:         }
                   2295:         if (@singledirfiles) {
1.1315    raeburn  2296:             $possdirs = 1;
1.1248    raeburn  2297:         }
                   2298:     }
                   2299:     if (($possdirs == 1) && (@singledirfiles)) {
                   2300:         my $showdir = $singledir;
                   2301:         if ($singledir eq '') {
                   2302:             $showdir = '/';
                   2303:         }
                   2304:         $output = $lt{'dire'}.
                   2305:                   '<select name="'.$firstselectname.'">'.
                   2306:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2307:                   '</select><br />'.
                   2308:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2309:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2310:         foreach my $file (@singledirfiles) {
                   2311:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2312:         }
                   2313:         $output .= '</select><br />'."\n";
                   2314:     }
                   2315:     return ($possdirs,$output);
                   2316: }
                   2317: 
1.565     albertel 2318: =pod
                   2319: 
1.256     matthew  2320: =head1 Excel and CSV file utility routines
                   2321: 
                   2322: =cut
                   2323: 
                   2324: ###############################################################
                   2325: ###############################################################
                   2326: 
                   2327: =pod
                   2328: 
1.1162    raeburn  2329: =over 4
                   2330: 
1.648     raeburn  2331: =item * &csv_translate($text) 
1.37      matthew  2332: 
1.185     www      2333: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2334: format.
                   2335: 
                   2336: =cut
                   2337: 
1.180     matthew  2338: ###############################################################
                   2339: ###############################################################
1.37      matthew  2340: sub csv_translate {
                   2341:     my $text = shift;
                   2342:     $text =~ s/\"/\"\"/g;
1.209     albertel 2343:     $text =~ s/\n/ /g;
1.37      matthew  2344:     return $text;
                   2345: }
1.180     matthew  2346: 
                   2347: ###############################################################
                   2348: ###############################################################
                   2349: 
                   2350: =pod
                   2351: 
1.648     raeburn  2352: =item * &define_excel_formats()
1.180     matthew  2353: 
                   2354: Define some commonly used Excel cell formats.
                   2355: 
                   2356: Currently supported formats:
                   2357: 
                   2358: =over 4
                   2359: 
                   2360: =item header
                   2361: 
                   2362: =item bold
                   2363: 
                   2364: =item h1
                   2365: 
                   2366: =item h2
                   2367: 
                   2368: =item h3
                   2369: 
1.256     matthew  2370: =item h4
                   2371: 
                   2372: =item i
                   2373: 
1.180     matthew  2374: =item date
                   2375: 
                   2376: =back
                   2377: 
                   2378: Inputs: $workbook
                   2379: 
                   2380: Returns: $format, a hash reference.
                   2381: 
1.1057    foxr     2382: 
1.180     matthew  2383: =cut
                   2384: 
                   2385: ###############################################################
                   2386: ###############################################################
                   2387: sub define_excel_formats {
                   2388:     my ($workbook) = @_;
                   2389:     my $format;
                   2390:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2391:                                                 bottom    => 1,
                   2392:                                                 align     => 'center');
                   2393:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2394:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2395:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2396:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2397:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2398:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2399:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2400:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2401:     return $format;
                   2402: }
                   2403: 
                   2404: ###############################################################
                   2405: ###############################################################
1.113     bowersj2 2406: 
                   2407: =pod
                   2408: 
1.648     raeburn  2409: =item * &create_workbook()
1.255     matthew  2410: 
                   2411: Create an Excel worksheet.  If it fails, output message on the
                   2412: request object and return undefs.
                   2413: 
                   2414: Inputs: Apache request object
                   2415: 
                   2416: Returns (undef) on failure, 
                   2417:     Excel worksheet object, scalar with filename, and formats 
                   2418:     from &Apache::loncommon::define_excel_formats on success
                   2419: 
                   2420: =cut
                   2421: 
                   2422: ###############################################################
                   2423: ###############################################################
                   2424: sub create_workbook {
                   2425:     my ($r) = @_;
                   2426:         #
                   2427:     # Create the excel spreadsheet
                   2428:     my $filename = '/prtspool/'.
1.258     albertel 2429:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2430:         time.'_'.rand(1000000000).'.xls';
                   2431:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2432:     if (! defined($workbook)) {
                   2433:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2434:         $r->print(
                   2435:             '<p class="LC_error">'
                   2436:            .&mt('Problems occurred in creating the new Excel file.')
                   2437:            .' '.&mt('This error has been logged.')
                   2438:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2439:            .'</p>'
                   2440:         );
1.255     matthew  2441:         return (undef);
                   2442:     }
                   2443:     #
1.1014    foxr     2444:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2445:     #
                   2446:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2447:     return ($workbook,$filename,$format);
                   2448: }
                   2449: 
                   2450: ###############################################################
                   2451: ###############################################################
                   2452: 
                   2453: =pod
                   2454: 
1.648     raeburn  2455: =item * &create_text_file()
1.113     bowersj2 2456: 
1.542     raeburn  2457: Create a file to write to and eventually make available to the user.
1.256     matthew  2458: If file creation fails, outputs an error message on the request object and 
                   2459: return undefs.
1.113     bowersj2 2460: 
1.256     matthew  2461: Inputs: Apache request object, and file suffix
1.113     bowersj2 2462: 
1.256     matthew  2463: Returns (undef) on failure, 
                   2464:     Filehandle and filename on success.
1.113     bowersj2 2465: 
                   2466: =cut
                   2467: 
1.256     matthew  2468: ###############################################################
                   2469: ###############################################################
                   2470: sub create_text_file {
                   2471:     my ($r,$suffix) = @_;
                   2472:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2473:     my $fh;
                   2474:     my $filename = '/prtspool/'.
1.258     albertel 2475:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2476:         time.'_'.rand(1000000000).'.'.$suffix;
                   2477:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2478:     if (! defined($fh)) {
                   2479:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2480:         $r->print(
                   2481:             '<p class="LC_error">'
                   2482:            .&mt('Problems occurred in creating the output file.')
                   2483:            .' '.&mt('This error has been logged.')
                   2484:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2485:            .'</p>'
                   2486:         );
1.113     bowersj2 2487:     }
1.256     matthew  2488:     return ($fh,$filename)
1.113     bowersj2 2489: }
                   2490: 
                   2491: 
1.256     matthew  2492: =pod 
1.113     bowersj2 2493: 
                   2494: =back
                   2495: 
                   2496: =cut
1.37      matthew  2497: 
                   2498: ###############################################################
1.33      matthew  2499: ##        Home server <option> list generating code          ##
                   2500: ###############################################################
1.35      matthew  2501: 
1.169     www      2502: # ------------------------------------------
                   2503: 
                   2504: sub domain_select {
1.1289    raeburn  2505:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2506:     my @possdoms;
                   2507:     if (ref($incdoms) eq 'ARRAY') {
                   2508:         @possdoms = @{$incdoms};
                   2509:     } else {
                   2510:         @possdoms = &Apache::lonnet::all_domains();
                   2511:     }
                   2512: 
1.169     www      2513:     my %domains=map { 
1.514     albertel 2514: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2515:     } @possdoms;
                   2516: 
                   2517:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2518:         foreach my $dom (@{$excdoms}) {
                   2519:             delete($domains{$dom});
                   2520:         }
                   2521:     }
                   2522: 
1.169     www      2523:     if ($multiple) {
                   2524: 	$domains{''}=&mt('Any domain');
1.550     albertel 2525: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2526: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2527:     } else {
1.550     albertel 2528: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2529: 	return &select_form($name,$value,\%domains);
1.169     www      2530:     }
                   2531: }
                   2532: 
1.282     albertel 2533: #-------------------------------------------
                   2534: 
                   2535: =pod
                   2536: 
1.519     raeburn  2537: =head1 Routines for form select boxes
                   2538: 
                   2539: =over 4
                   2540: 
1.648     raeburn  2541: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2542: 
                   2543: Returns a string containing a <select> element int multiple mode
                   2544: 
                   2545: 
                   2546: Args:
                   2547:   $name - name of the <select> element
1.506     raeburn  2548:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2549:   $size - number of rows long the select element is
1.283     albertel 2550:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2551:           (shown text should already have been &mt())
1.506     raeburn  2552:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2553: 
1.282     albertel 2554: =cut
                   2555: 
                   2556: #-------------------------------------------
1.169     www      2557: sub multiple_select_form {
1.284     albertel 2558:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2559:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2560:     my $output='';
1.191     matthew  2561:     if (! defined($size)) {
                   2562:         $size = 4;
1.283     albertel 2563:         if (scalar(keys(%$hash))<4) {
                   2564:             $size = scalar(keys(%$hash));
1.191     matthew  2565:         }
                   2566:     }
1.734     bisitz   2567:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2568:     my @order;
1.506     raeburn  2569:     if (ref($order) eq 'ARRAY')  {
                   2570:         @order = @{$order};
                   2571:     } else {
                   2572:         @order = sort(keys(%$hash));
1.501     banghart 2573:     }
                   2574:     if (exists($$hash{'select_form_order'})) {
                   2575:         @order = @{$$hash{'select_form_order'}};
                   2576:     }
                   2577:         
1.284     albertel 2578:     foreach my $key (@order) {
1.356     albertel 2579:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2580:         $output.='selected="selected" ' if ($selected{$key});
                   2581:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2582:     }
                   2583:     $output.="</select>\n";
                   2584:     return $output;
                   2585: }
                   2586: 
1.88      www      2587: #-------------------------------------------
                   2588: 
                   2589: =pod
                   2590: 
1.1254    raeburn  2591: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2592: 
                   2593: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2594: allow a user to select options from a ref to a hash containing:
                   2595: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2596: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2597: An optional arg -- $readonly -- if true will cause the select form
                   2598: to be disabled, e.g., for the case where an instructor has a section-
                   2599: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2600: 
1.88      www      2601: See lonrights.pm for an example invocation and use.
                   2602: 
                   2603: =cut
                   2604: 
                   2605: #-------------------------------------------
                   2606: sub select_form {
1.1228    raeburn  2607:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2608:     return unless (ref($hashref) eq 'HASH');
                   2609:     if ($onchange) {
                   2610:         $onchange = ' onchange="'.$onchange.'"';
                   2611:     }
1.1228    raeburn  2612:     my $disabled;
                   2613:     if ($readonly) {
                   2614:         $disabled = ' disabled="disabled"';
                   2615:     }
                   2616:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2617:     my @keys;
1.970     raeburn  2618:     if (exists($hashref->{'select_form_order'})) {
                   2619: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2620:     } else {
1.970     raeburn  2621: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2622:     }
1.356     albertel 2623:     foreach my $key (@keys) {
                   2624:         $selectform.=
                   2625: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2626:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2627:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2628:     }
                   2629:     $selectform.="</select>";
                   2630:     return $selectform;
                   2631: }
                   2632: 
1.475     www      2633: # For display filters
                   2634: 
                   2635: sub display_filter {
1.1074    raeburn  2636:     my ($context) = @_;
1.475     www      2637:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2638:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2639:     my $phraseinput = 'hidden';
                   2640:     my $includeinput = 'hidden';
                   2641:     my ($checked,$includetypestext);
                   2642:     if ($env{'form.displayfilter'} eq 'containing') {
                   2643:         $phraseinput = 'text'; 
                   2644:         if ($context eq 'parmslog') {
                   2645:             $includeinput = 'checkbox';
                   2646:             if ($env{'form.includetypes'}) {
                   2647:                 $checked = ' checked="checked"';
                   2648:             }
                   2649:             $includetypestext = &mt('Include parameter types');
                   2650:         }
                   2651:     } else {
                   2652:         $includetypestext = '&nbsp;';
                   2653:     }
                   2654:     my ($additional,$secondid,$thirdid);
                   2655:     if ($context eq 'parmslog') {
                   2656:         $additional = 
                   2657:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2658:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2659:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2660:             '</label>';
                   2661:         $secondid = 'includetypes';
                   2662:         $thirdid = 'includetypestext';
                   2663:     }
                   2664:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2665:                                                     '$secondid','$thirdid')";
                   2666:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2667: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2668: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2669: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2670:            &mt('Filter: [_1]',
1.477     www      2671: 	   &select_form($env{'form.displayfilter'},
                   2672: 			'displayfilter',
1.970     raeburn  2673: 			{'currentfolder' => 'Current folder/page',
1.477     www      2674: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2675: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2676: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2677:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2678:                          '" />'.$additional;
                   2679: }
                   2680: 
                   2681: sub display_filter_js {
                   2682:     my $includetext = &mt('Include parameter types');
                   2683:     return <<"ENDJS";
                   2684:   
                   2685: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2686:     var firstType = 'hidden';
                   2687:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2688:         firstType = 'text';
                   2689:     }
                   2690:     firstObject = document.getElementById(firstid);
                   2691:     if (typeof(firstObject) == 'object') {
                   2692:         if (firstObject.type != firstType) {
                   2693:             changeInputType(firstObject,firstType);
                   2694:         }
                   2695:     }
                   2696:     if (context == 'parmslog') {
                   2697:         var secondType = 'hidden';
                   2698:         if (firstType == 'text') {
                   2699:             secondType = 'checkbox';
                   2700:         }
                   2701:         secondObject = document.getElementById(secondid);  
                   2702:         if (typeof(secondObject) == 'object') {
                   2703:             if (secondObject.type != secondType) {
                   2704:                 changeInputType(secondObject,secondType);
                   2705:             }
                   2706:         }
                   2707:         var textItem = document.getElementById(thirdid);
                   2708:         var currtext = textItem.innerHTML;
                   2709:         var newtext;
                   2710:         if (firstType == 'text') {
                   2711:             newtext = '$includetext';
                   2712:         } else {
                   2713:             newtext = '&nbsp;';
                   2714:         }
                   2715:         if (currtext != newtext) {
                   2716:             textItem.innerHTML = newtext;
                   2717:         }
                   2718:     }
                   2719:     return;
                   2720: }
                   2721: 
                   2722: function changeInputType(oldObject,newType) {
                   2723:     var newObject = document.createElement('input');
                   2724:     newObject.type = newType;
                   2725:     if (oldObject.size) {
                   2726:         newObject.size = oldObject.size;
                   2727:     }
                   2728:     if (oldObject.value) {
                   2729:         newObject.value = oldObject.value;
                   2730:     }
                   2731:     if (oldObject.name) {
                   2732:         newObject.name = oldObject.name;
                   2733:     }
                   2734:     if (oldObject.id) {
                   2735:         newObject.id = oldObject.id;
                   2736:     }
                   2737:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2738:     return;
                   2739: }
                   2740: 
                   2741: ENDJS
1.475     www      2742: }
                   2743: 
1.167     www      2744: sub gradeleveldescription {
                   2745:     my $gradelevel=shift;
                   2746:     my %gradelevels=(0 => 'Not specified',
                   2747: 		     1 => 'Grade 1',
                   2748: 		     2 => 'Grade 2',
                   2749: 		     3 => 'Grade 3',
                   2750: 		     4 => 'Grade 4',
                   2751: 		     5 => 'Grade 5',
                   2752: 		     6 => 'Grade 6',
                   2753: 		     7 => 'Grade 7',
                   2754: 		     8 => 'Grade 8',
                   2755: 		     9 => 'Grade 9',
                   2756: 		     10 => 'Grade 10',
                   2757: 		     11 => 'Grade 11',
                   2758: 		     12 => 'Grade 12',
                   2759: 		     13 => 'Grade 13',
                   2760: 		     14 => '100 Level',
                   2761: 		     15 => '200 Level',
                   2762: 		     16 => '300 Level',
                   2763: 		     17 => '400 Level',
                   2764: 		     18 => 'Graduate Level');
                   2765:     return &mt($gradelevels{$gradelevel});
                   2766: }
                   2767: 
1.163     www      2768: sub select_level_form {
                   2769:     my ($deflevel,$name)=@_;
                   2770:     unless ($deflevel) { $deflevel=0; }
1.167     www      2771:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2772:     for (my $i=0; $i<=18; $i++) {
                   2773:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2774:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2775:                 ">".&gradeleveldescription($i)."</option>\n";
                   2776:     }
                   2777:     $selectform.="</select>";
                   2778:     return $selectform;
1.163     www      2779: }
1.167     www      2780: 
1.35      matthew  2781: #-------------------------------------------
                   2782: 
1.45      matthew  2783: =pod
                   2784: 
1.1256    raeburn  2785: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2786: 
                   2787: Returns a string containing a <select name='$name' size='1'> form to 
                   2788: allow a user to select the domain to preform an operation in.  
                   2789: See loncreateuser.pm for an example invocation and use.
                   2790: 
1.90      www      2791: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2792: selected");
                   2793: 
1.743     raeburn  2794: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2795: 
1.910     raeburn  2796: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2797: 
1.1121    raeburn  2798: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2799: 
                   2800: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2801: 
1.1256    raeburn  2802: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2803: 
1.35      matthew  2804: =cut
                   2805: 
                   2806: #-------------------------------------------
1.34      matthew  2807: sub select_dom_form {
1.1256    raeburn  2808:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2809:     if ($onchange) {
1.874     raeburn  2810:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2811:     }
1.1256    raeburn  2812:     if ($disabled) {
                   2813:         $disabled = ' disabled="disabled"';
                   2814:     }
1.1121    raeburn  2815:     my (@domains,%exclude);
1.910     raeburn  2816:     if (ref($incdoms) eq 'ARRAY') {
                   2817:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2818:     } else {
                   2819:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2820:     }
1.90      www      2821:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2822:     if (ref($excdoms) eq 'ARRAY') {
                   2823:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2824:     }
1.1256    raeburn  2825:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2826:     foreach my $dom (@domains) {
1.1121    raeburn  2827:         next if ($exclude{$dom});
1.356     albertel 2828:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2829:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2830:         if ($showdomdesc) {
                   2831:             if ($dom ne '') {
                   2832:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2833:                 if ($domdesc ne '') {
                   2834:                     $selectdomain .= ' ('.$domdesc.')';
                   2835:                 }
                   2836:             } 
                   2837:         }
                   2838:         $selectdomain .= "</option>\n";
1.34      matthew  2839:     }
                   2840:     $selectdomain.="</select>";
                   2841:     return $selectdomain;
                   2842: }
                   2843: 
1.35      matthew  2844: #-------------------------------------------
                   2845: 
1.45      matthew  2846: =pod
                   2847: 
1.648     raeburn  2848: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2849: 
1.586     raeburn  2850: input: 4 arguments (two required, two optional) - 
                   2851:     $domain - domain of new user
                   2852:     $name - name of form element
                   2853:     $default - Value of 'default' causes a default item to be first 
                   2854:                             option, and selected by default. 
                   2855:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2856:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2857: output: returns 2 items: 
1.586     raeburn  2858: (a) form element which contains either:
                   2859:    (i) <select name="$name">
                   2860:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2861:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2862:        </select>
                   2863:        form item if there are multiple library servers in $domain, or
                   2864:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2865:        if there is only one library server in $domain.
                   2866: 
                   2867: (b) number of library servers found.
                   2868: 
                   2869: See loncreateuser.pm for example of use.
1.35      matthew  2870: 
                   2871: =cut
                   2872: 
                   2873: #-------------------------------------------
1.586     raeburn  2874: sub home_server_form_item {
                   2875:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2876:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2877:     my $result;
                   2878:     my $numlib = keys(%servers);
                   2879:     if ($numlib > 1) {
                   2880:         $result .= '<select name="'.$name.'" />'."\n";
                   2881:         if ($default) {
1.804     bisitz   2882:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2883:                        '</option>'."\n";
                   2884:         }
                   2885:         foreach my $hostid (sort(keys(%servers))) {
                   2886:             $result.= '<option value="'.$hostid.'">'.
                   2887: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2888:         }
                   2889:         $result .= '</select>'."\n";
                   2890:     } elsif ($numlib == 1) {
                   2891:         my $hostid;
                   2892:         foreach my $item (keys(%servers)) {
                   2893:             $hostid = $item;
                   2894:         }
                   2895:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2896:                    $hostid.'" />';
                   2897:                    if (!$hide) {
                   2898:                        $result .= $hostid.' '.$servers{$hostid};
                   2899:                    }
                   2900:                    $result .= "\n";
                   2901:     } elsif ($default) {
                   2902:         $result .= '<input type="hidden" name="'.$name.
                   2903:                    '" value="default" />';
                   2904:                    if (!$hide) {
                   2905:                        $result .= &mt('default');
                   2906:                    }
                   2907:                    $result .= "\n";
1.33      matthew  2908:     }
1.586     raeburn  2909:     return ($result,$numlib);
1.33      matthew  2910: }
1.112     bowersj2 2911: 
                   2912: =pod
                   2913: 
1.534     albertel 2914: =back 
                   2915: 
1.112     bowersj2 2916: =cut
1.87      matthew  2917: 
                   2918: ###############################################################
1.112     bowersj2 2919: ##                  Decoding User Agent                      ##
1.87      matthew  2920: ###############################################################
                   2921: 
                   2922: =pod
                   2923: 
1.112     bowersj2 2924: =head1 Decoding the User Agent
                   2925: 
                   2926: =over 4
                   2927: 
                   2928: =item * &decode_user_agent()
1.87      matthew  2929: 
                   2930: Inputs: $r
                   2931: 
                   2932: Outputs:
                   2933: 
                   2934: =over 4
                   2935: 
1.112     bowersj2 2936: =item * $httpbrowser
1.87      matthew  2937: 
1.112     bowersj2 2938: =item * $clientbrowser
1.87      matthew  2939: 
1.112     bowersj2 2940: =item * $clientversion
1.87      matthew  2941: 
1.112     bowersj2 2942: =item * $clientmathml
1.87      matthew  2943: 
1.112     bowersj2 2944: =item * $clientunicode
1.87      matthew  2945: 
1.112     bowersj2 2946: =item * $clientos
1.87      matthew  2947: 
1.1137    raeburn  2948: =item * $clientmobile
                   2949: 
1.1141    raeburn  2950: =item * $clientinfo
                   2951: 
1.1194    raeburn  2952: =item * $clientosversion
                   2953: 
1.87      matthew  2954: =back
                   2955: 
1.157     matthew  2956: =back 
                   2957: 
1.87      matthew  2958: =cut
                   2959: 
                   2960: ###############################################################
                   2961: ###############################################################
                   2962: sub decode_user_agent {
1.247     albertel 2963:     my ($r)=@_;
1.87      matthew  2964:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2965:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2966:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2967:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2968:     my $clientbrowser='unknown';
                   2969:     my $clientversion='0';
                   2970:     my $clientmathml='';
                   2971:     my $clientunicode='0';
1.1137    raeburn  2972:     my $clientmobile=0;
1.1194    raeburn  2973:     my $clientosversion='';
1.87      matthew  2974:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2975:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2976: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2977: 	    $clientbrowser=$bname;
                   2978:             $httpbrowser=~/$vreg/i;
                   2979: 	    $clientversion=$1;
                   2980:             $clientmathml=($clientversion>=$minv);
                   2981:             $clientunicode=($clientversion>=$univ);
                   2982: 	}
                   2983:     }
                   2984:     my $clientos='unknown';
1.1141    raeburn  2985:     my $clientinfo;
1.87      matthew  2986:     if (($httpbrowser=~/linux/i) ||
                   2987:         ($httpbrowser=~/unix/i) ||
                   2988:         ($httpbrowser=~/ux/i) ||
                   2989:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2990:     if (($httpbrowser=~/vax/i) ||
                   2991:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2992:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2993:     if (($httpbrowser=~/mac/i) ||
                   2994:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2995:     if ($httpbrowser=~/win/i) {
                   2996:         $clientos='win';
                   2997:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2998:             $clientosversion = $1;
                   2999:         }
                   3000:     }
1.87      matthew  3001:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3002:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3003:         $clientmobile=lc($1);
                   3004:     }
1.1141    raeburn  3005:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3006:         $clientinfo = 'firefox-'.$1;
                   3007:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3008:         $clientinfo = 'chromeframe-'.$1;
                   3009:     }
1.87      matthew  3010:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3011:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3012:             $clientosversion);
1.87      matthew  3013: }
                   3014: 
1.32      matthew  3015: ###############################################################
                   3016: ##    Authentication changing form generation subroutines    ##
                   3017: ###############################################################
                   3018: ##
                   3019: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3020: ## hash, and have reasonable default values.
                   3021: ##
                   3022: ##    formname = the name given in the <form> tag.
1.35      matthew  3023: #-------------------------------------------
                   3024: 
1.45      matthew  3025: =pod
                   3026: 
1.112     bowersj2 3027: =head1 Authentication Routines
                   3028: 
                   3029: =over 4
                   3030: 
1.648     raeburn  3031: =item * &authform_xxxxxx()
1.35      matthew  3032: 
                   3033: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3034: handle some of the conveniences required for authentication forms.  
                   3035: This is not an optimal method, but it works.  
                   3036: 
                   3037: =over 4
                   3038: 
1.112     bowersj2 3039: =item * authform_header
1.35      matthew  3040: 
1.112     bowersj2 3041: =item * authform_authorwarning
1.35      matthew  3042: 
1.112     bowersj2 3043: =item * authform_nochange
1.35      matthew  3044: 
1.112     bowersj2 3045: =item * authform_kerberos
1.35      matthew  3046: 
1.112     bowersj2 3047: =item * authform_internal
1.35      matthew  3048: 
1.112     bowersj2 3049: =item * authform_filesystem
1.35      matthew  3050: 
1.1310    raeburn  3051: =item * authform_lti
                   3052: 
1.35      matthew  3053: =back
                   3054: 
1.648     raeburn  3055: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3056: 
1.35      matthew  3057: =cut
                   3058: 
                   3059: #-------------------------------------------
1.32      matthew  3060: sub authform_header{  
                   3061:     my %in = (
                   3062:         formname => 'cu',
1.80      albertel 3063:         kerb_def_dom => '',
1.32      matthew  3064:         @_,
                   3065:     );
                   3066:     $in{'formname'} = 'document.' . $in{'formname'};
                   3067:     my $result='';
1.80      albertel 3068: 
                   3069: #---------------------------------------------- Code for upper case translation
                   3070:     my $Javascript_toUpperCase;
                   3071:     unless ($in{kerb_def_dom}) {
                   3072:         $Javascript_toUpperCase =<<"END";
                   3073:         switch (choice) {
                   3074:            case 'krb': currentform.elements[choicearg].value =
                   3075:                currentform.elements[choicearg].value.toUpperCase();
                   3076:                break;
                   3077:            default:
                   3078:         }
                   3079: END
                   3080:     } else {
                   3081:         $Javascript_toUpperCase = "";
                   3082:     }
                   3083: 
1.165     raeburn  3084:     my $radioval = "'nochange'";
1.591     raeburn  3085:     if (defined($in{'curr_authtype'})) {
                   3086:         if ($in{'curr_authtype'} ne '') {
                   3087:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3088:         }
1.174     matthew  3089:     }
1.165     raeburn  3090:     my $argfield = 'null';
1.591     raeburn  3091:     if (defined($in{'mode'})) {
1.165     raeburn  3092:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3093:             if (defined($in{'curr_autharg'})) {
                   3094:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3095:                     $argfield = "'$in{'curr_autharg'}'";
                   3096:                 }
                   3097:             }
                   3098:         }
                   3099:     }
                   3100: 
1.32      matthew  3101:     $result.=<<"END";
                   3102: var current = new Object();
1.165     raeburn  3103: current.radiovalue = $radioval;
                   3104: current.argfield = $argfield;
1.32      matthew  3105: 
                   3106: function changed_radio(choice,currentform) {
                   3107:     var choicearg = choice + 'arg';
                   3108:     // If a radio button in changed, we need to change the argfield
                   3109:     if (current.radiovalue != choice) {
                   3110:         current.radiovalue = choice;
                   3111:         if (current.argfield != null) {
                   3112:             currentform.elements[current.argfield].value = '';
                   3113:         }
                   3114:         if (choice == 'nochange') {
                   3115:             current.argfield = null;
                   3116:         } else {
                   3117:             current.argfield = choicearg;
                   3118:             switch(choice) {
                   3119:                 case 'krb': 
                   3120:                     currentform.elements[current.argfield].value = 
                   3121:                         "$in{'kerb_def_dom'}";
                   3122:                 break;
                   3123:               default:
                   3124:                 break;
                   3125:             }
                   3126:         }
                   3127:     }
                   3128:     return;
                   3129: }
1.22      www      3130: 
1.32      matthew  3131: function changed_text(choice,currentform) {
                   3132:     var choicearg = choice + 'arg';
                   3133:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3134:         $Javascript_toUpperCase
1.32      matthew  3135:         // clear old field
                   3136:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3137:             currentform.elements[current.argfield].value = '';
                   3138:         }
                   3139:         current.argfield = choicearg;
                   3140:     }
                   3141:     set_auth_radio_buttons(choice,currentform);
                   3142:     return;
1.20      www      3143: }
1.32      matthew  3144: 
                   3145: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3146:     var numauthchoices = currentform.login.length;
                   3147:     if (typeof numauthchoices  == "undefined") {
                   3148:         return;
                   3149:     } 
1.32      matthew  3150:     var i=0;
1.986     raeburn  3151:     while (i < numauthchoices) {
1.32      matthew  3152:         if (currentform.login[i].value == newvalue) { break; }
                   3153:         i++;
                   3154:     }
1.986     raeburn  3155:     if (i == numauthchoices) {
1.32      matthew  3156:         return;
                   3157:     }
                   3158:     current.radiovalue = newvalue;
                   3159:     currentform.login[i].checked = true;
                   3160:     return;
                   3161: }
                   3162: END
                   3163:     return $result;
                   3164: }
                   3165: 
1.1106    raeburn  3166: sub authform_authorwarning {
1.32      matthew  3167:     my $result='';
1.144     matthew  3168:     $result='<i>'.
                   3169:         &mt('As a general rule, only authors or co-authors should be '.
                   3170:             'filesystem authenticated '.
                   3171:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3172:     return $result;
                   3173: }
                   3174: 
1.1106    raeburn  3175: sub authform_nochange {
1.32      matthew  3176:     my %in = (
                   3177:               formname => 'document.cu',
                   3178:               kerb_def_dom => 'MSU.EDU',
                   3179:               @_,
                   3180:           );
1.1106    raeburn  3181:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3182:     my $result;
1.1104    raeburn  3183:     if (!$authnum) {
1.1105    raeburn  3184:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3185:     } else {
                   3186:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3187:                   '<input type="radio" name="login" value="nochange" '.
                   3188:                   'checked="checked" onclick="'.
1.281     albertel 3189:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3190: 	    '</label>';
1.586     raeburn  3191:     }
1.32      matthew  3192:     return $result;
                   3193: }
                   3194: 
1.591     raeburn  3195: sub authform_kerberos {
1.32      matthew  3196:     my %in = (
                   3197:               formname => 'document.cu',
                   3198:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3199:               kerb_def_auth => 'krb4',
1.32      matthew  3200:               @_,
                   3201:               );
1.586     raeburn  3202:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3203:         $autharg,$jscall,$disabled);
1.1106    raeburn  3204:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3205:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3206:        $check5 = ' checked="checked"';
1.80      albertel 3207:     } else {
1.772     bisitz   3208:        $check4 = ' checked="checked"';
1.80      albertel 3209:     }
1.1259    raeburn  3210:     if ($in{'readonly'}) {
                   3211:         $disabled = ' disabled="disabled"';
                   3212:     }
1.165     raeburn  3213:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3214:     if (defined($in{'curr_authtype'})) {
                   3215:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3216:             $krbcheck = ' checked="checked"';
1.623     raeburn  3217:             if (defined($in{'mode'})) {
                   3218:                 if ($in{'mode'} eq 'modifyuser') {
                   3219:                     $krbcheck = '';
                   3220:                 }
                   3221:             }
1.591     raeburn  3222:             if (defined($in{'curr_kerb_ver'})) {
                   3223:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3224:                     $check5 = ' checked="checked"';
1.591     raeburn  3225:                     $check4 = '';
                   3226:                 } else {
1.772     bisitz   3227:                     $check4 = ' checked="checked"';
1.591     raeburn  3228:                     $check5 = '';
                   3229:                 }
1.586     raeburn  3230:             }
1.591     raeburn  3231:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3232:                 $krbarg = $in{'curr_autharg'};
                   3233:             }
1.586     raeburn  3234:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3235:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3236:                     $result = 
                   3237:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3238:         $in{'curr_autharg'},$krbver);
                   3239:                 } else {
                   3240:                     $result =
                   3241:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3242:                 }
                   3243:                 return $result; 
                   3244:             }
                   3245:         }
                   3246:     } else {
                   3247:         if ($authnum == 1) {
1.784     bisitz   3248:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3249:         }
                   3250:     }
1.586     raeburn  3251:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3252:         return;
1.587     raeburn  3253:     } elsif ($authtype eq '') {
1.591     raeburn  3254:         if (defined($in{'mode'})) {
1.587     raeburn  3255:             if ($in{'mode'} eq 'modifycourse') {
                   3256:                 if ($authnum == 1) {
1.1259    raeburn  3257:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3258:                 }
                   3259:             }
                   3260:         }
1.586     raeburn  3261:     }
                   3262:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3263:     if ($authtype eq '') {
                   3264:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3265:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3266:                     $krbcheck.$disabled.' />';
1.586     raeburn  3267:     }
                   3268:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3269:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3270:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3271:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3272:          $in{'curr_authtype'} eq 'krb4')) {
                   3273:         $result .= &mt
1.144     matthew  3274:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3275:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3276:          '<label>'.$authtype,
1.281     albertel 3277:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3278:              'value="'.$krbarg.'" '.
1.1259    raeburn  3279:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3280:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3281:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3282: 	 '</label>');
1.586     raeburn  3283:     } elsif ($can_assign{'krb4'}) {
                   3284:         $result .= &mt
                   3285:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3286:          '[_3] Version 4 [_4]',
                   3287:          '<label>'.$authtype,
                   3288:          '</label><input type="text" size="10" name="krbarg" '.
                   3289:              'value="'.$krbarg.'" '.
1.1259    raeburn  3290:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3291:          '<label><input type="hidden" name="krbver" value="4" />',
                   3292:          '</label>');
                   3293:     } elsif ($can_assign{'krb5'}) {
                   3294:         $result .= &mt
                   3295:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3296:          '[_3] Version 5 [_4]',
                   3297:          '<label>'.$authtype,
                   3298:          '</label><input type="text" size="10" name="krbarg" '.
                   3299:              'value="'.$krbarg.'" '.
1.1259    raeburn  3300:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3301:          '<label><input type="hidden" name="krbver" value="5" />',
                   3302:          '</label>');
                   3303:     }
1.32      matthew  3304:     return $result;
                   3305: }
                   3306: 
1.1106    raeburn  3307: sub authform_internal {
1.586     raeburn  3308:     my %in = (
1.32      matthew  3309:                 formname => 'document.cu',
                   3310:                 kerb_def_dom => 'MSU.EDU',
                   3311:                 @_,
                   3312:                 );
1.1259    raeburn  3313:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3314:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3315:     if ($in{'readonly'}) {
                   3316:         $disabled = ' disabled="disabled"';
                   3317:     }
1.591     raeburn  3318:     if (defined($in{'curr_authtype'})) {
                   3319:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3320:             if ($can_assign{'int'}) {
1.772     bisitz   3321:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3322:                 if (defined($in{'mode'})) {
                   3323:                     if ($in{'mode'} eq 'modifyuser') {
                   3324:                         $intcheck = '';
                   3325:                     }
                   3326:                 }
1.591     raeburn  3327:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3328:                     $intarg = $in{'curr_autharg'};
                   3329:                 }
                   3330:             } else {
                   3331:                 $result = &mt('Currently internally authenticated.');
                   3332:                 return $result;
1.165     raeburn  3333:             }
                   3334:         }
1.586     raeburn  3335:     } else {
                   3336:         if ($authnum == 1) {
1.784     bisitz   3337:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3338:         }
                   3339:     }
                   3340:     if (!$can_assign{'int'}) {
                   3341:         return;
1.587     raeburn  3342:     } elsif ($authtype eq '') {
1.591     raeburn  3343:         if (defined($in{'mode'})) {
1.587     raeburn  3344:             if ($in{'mode'} eq 'modifycourse') {
                   3345:                 if ($authnum == 1) {
1.1259    raeburn  3346:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3347:                 }
                   3348:             }
                   3349:         }
1.165     raeburn  3350:     }
1.586     raeburn  3351:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3352:     if ($authtype eq '') {
                   3353:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3354:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3355:     }
1.605     bisitz   3356:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3357:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3358:     $result = &mt
1.144     matthew  3359:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3360:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3361:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3362:     return $result;
                   3363: }
                   3364: 
1.1104    raeburn  3365: sub authform_local {
1.32      matthew  3366:     my %in = (
                   3367:               formname => 'document.cu',
                   3368:               kerb_def_dom => 'MSU.EDU',
                   3369:               @_,
                   3370:               );
1.1259    raeburn  3371:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3372:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3373:     if ($in{'readonly'}) {
                   3374:         $disabled = ' disabled="disabled"';
                   3375:     } 
1.591     raeburn  3376:     if (defined($in{'curr_authtype'})) {
                   3377:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3378:             if ($can_assign{'loc'}) {
1.772     bisitz   3379:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3380:                 if (defined($in{'mode'})) {
                   3381:                     if ($in{'mode'} eq 'modifyuser') {
                   3382:                         $loccheck = '';
                   3383:                     }
                   3384:                 }
1.591     raeburn  3385:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3386:                     $locarg = $in{'curr_autharg'};
                   3387:                 }
                   3388:             } else {
                   3389:                 $result = &mt('Currently using local (institutional) authentication.');
                   3390:                 return $result;
1.165     raeburn  3391:             }
                   3392:         }
1.586     raeburn  3393:     } else {
                   3394:         if ($authnum == 1) {
1.784     bisitz   3395:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3396:         }
                   3397:     }
                   3398:     if (!$can_assign{'loc'}) {
                   3399:         return;
1.587     raeburn  3400:     } elsif ($authtype eq '') {
1.591     raeburn  3401:         if (defined($in{'mode'})) {
1.587     raeburn  3402:             if ($in{'mode'} eq 'modifycourse') {
                   3403:                 if ($authnum == 1) {
1.1259    raeburn  3404:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3405:                 }
                   3406:             }
                   3407:         }
1.165     raeburn  3408:     }
1.586     raeburn  3409:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3410:     if ($authtype eq '') {
                   3411:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3412:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3413:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3414:     }
                   3415:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3416:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3417:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3418:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3419:     return $result;
                   3420: }
                   3421: 
1.1106    raeburn  3422: sub authform_filesystem {
1.32      matthew  3423:     my %in = (
                   3424:               formname => 'document.cu',
                   3425:               kerb_def_dom => 'MSU.EDU',
                   3426:               @_,
                   3427:               );
1.1259    raeburn  3428:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3429:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3430:     if ($in{'readonly'}) {
                   3431:         $disabled = ' disabled="disabled"';
                   3432:     }
1.591     raeburn  3433:     if (defined($in{'curr_authtype'})) {
                   3434:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3435:             if ($can_assign{'fsys'}) {
1.772     bisitz   3436:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3437:                 if (defined($in{'mode'})) {
                   3438:                     if ($in{'mode'} eq 'modifyuser') {
                   3439:                         $fsyscheck = '';
                   3440:                     }
                   3441:                 }
1.586     raeburn  3442:             } else {
                   3443:                 $result = &mt('Currently Filesystem Authenticated.');
                   3444:                 return $result;
1.1259    raeburn  3445:             }
1.586     raeburn  3446:         }
                   3447:     } else {
                   3448:         if ($authnum == 1) {
1.784     bisitz   3449:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3450:         }
                   3451:     }
                   3452:     if (!$can_assign{'fsys'}) {
                   3453:         return;
1.587     raeburn  3454:     } elsif ($authtype eq '') {
1.591     raeburn  3455:         if (defined($in{'mode'})) {
1.587     raeburn  3456:             if ($in{'mode'} eq 'modifycourse') {
                   3457:                 if ($authnum == 1) {
1.1259    raeburn  3458:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3459:                 }
                   3460:             }
                   3461:         }
1.586     raeburn  3462:     }
                   3463:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3464:     if ($authtype eq '') {
                   3465:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3466:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3467:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3468:     }
1.1310    raeburn  3469:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3470:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3471:     $result = &mt
1.144     matthew  3472:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3473:          '<label>'.$authtype,'</label>'.$autharg);
                   3474:     return $result;
                   3475: }
                   3476: 
                   3477: sub authform_lti {
                   3478:     my %in = (
                   3479:               formname => 'document.cu',
                   3480:               kerb_def_dom => 'MSU.EDU',
                   3481:               @_,
                   3482:               );
                   3483:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3484:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3485:     if ($in{'readonly'}) {
                   3486:         $disabled = ' disabled="disabled"';
                   3487:     }
                   3488:     if (defined($in{'curr_authtype'})) {
                   3489:         if ($in{'curr_authtype'} eq 'lti') {
                   3490:             if ($can_assign{'lti'}) {
                   3491:                 $lticheck = 'checked="checked" ';
                   3492:                 if (defined($in{'mode'})) {
                   3493:                     if ($in{'mode'} eq 'modifyuser') {
                   3494:                         $lticheck = '';
                   3495:                     }
                   3496:                 }
                   3497:             } else {
                   3498:                 $result = &mt('Currently LTI Authenticated.');
                   3499:                 return $result;
                   3500:             }
                   3501:         }
                   3502:     } else {
                   3503:         if ($authnum == 1) {
                   3504:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3505:         }
                   3506:     }
                   3507:     if (!$can_assign{'lti'}) {
                   3508:         return;
                   3509:     } elsif ($authtype eq '') {
                   3510:         if (defined($in{'mode'})) {
                   3511:             if ($in{'mode'} eq 'modifycourse') {
                   3512:                 if ($authnum == 1) {
                   3513:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3514:                 }
                   3515:             }
                   3516:         }
                   3517:     }
                   3518:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3519:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3520:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3521:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3522:                     $jscall.'"'.$disabled.' />';
                   3523:     }
                   3524:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3525:     if ($authtype) {
                   3526:         $result = &mt('[_1] LTI Authenticated',
                   3527:                       '<label>'.$authtype.'</label>'.$autharg);
                   3528:     } else {
                   3529:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3530:                   $autharg;
                   3531:     }
1.32      matthew  3532:     return $result;
                   3533: }
                   3534: 
1.586     raeburn  3535: sub get_assignable_auth {
                   3536:     my ($dom) = @_;
                   3537:     if ($dom eq '') {
                   3538:         $dom = $env{'request.role.domain'};
                   3539:     }
                   3540:     my %can_assign = (
                   3541:                           krb4 => 1,
                   3542:                           krb5 => 1,
                   3543:                           int  => 1,
                   3544:                           loc  => 1,
1.1310    raeburn  3545:                           lti  => 1,
1.586     raeburn  3546:                      );
                   3547:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3548:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3549:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3550:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3551:             my $context;
                   3552:             if ($env{'request.role'} =~ /^au/) {
                   3553:                 $context = 'author';
1.1259    raeburn  3554:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3555:                 $context = 'domain';
                   3556:             } elsif ($env{'request.course.id'}) {
                   3557:                 $context = 'course';
                   3558:             }
                   3559:             if ($context) {
                   3560:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3561:                    %can_assign = %{$authhash->{$context}}; 
                   3562:                 }
                   3563:             }
                   3564:         }
                   3565:     }
                   3566:     my $authnum = 0;
                   3567:     foreach my $key (keys(%can_assign)) {
                   3568:         if ($can_assign{$key}) {
                   3569:             $authnum ++;
                   3570:         }
                   3571:     }
                   3572:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3573:         $authnum --;
                   3574:     }
                   3575:     return ($authnum,%can_assign);
                   3576: }
                   3577: 
1.1331    raeburn  3578: sub check_passwd_rules {
                   3579:     my ($domain,$plainpass) = @_;
                   3580:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3581:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3582:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3583:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3584:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3585:             if ($passwdconf{'min'} > $min) {
                   3586:                 $min = $passwdconf{'min'};
                   3587:             }
1.1331    raeburn  3588:         }
                   3589:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3590:             $max = $passwdconf{'max'};
                   3591:         }
                   3592:         @chars = @{$passwdconf{'chars'}};
                   3593:     }
                   3594:     if (($min) && (length($plainpass) < $min)) {
                   3595:         push(@brokerule,'min');
                   3596:     }
                   3597:     if (($max) && (length($plainpass) > $max)) {
                   3598:         push(@brokerule,'max');
                   3599:     }
                   3600:     if (@chars) {
                   3601:         my %rules;
                   3602:         map { $rules{$_} = 1; } @chars;
                   3603:         if ($rules{'uc'}) {
                   3604:             unless ($plainpass =~ /[A-Z]/) {
                   3605:                 push(@brokerule,'uc');
                   3606:             }
                   3607:         }
                   3608:         if ($rules{'lc'}) {
1.1332    raeburn  3609:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3610:                 push(@brokerule,'lc');
                   3611:             }
                   3612:         }
                   3613:         if ($rules{'num'}) {
                   3614:             unless ($plainpass =~ /\d/) {
                   3615:                 push(@brokerule,'num');
                   3616:             }
                   3617:         }
                   3618:         if ($rules{'spec'}) {
                   3619:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3620:                 push(@brokerule,'spec');
                   3621:             }
                   3622:         }
                   3623:     }
                   3624:     if (@brokerule) {
                   3625:         my %rulenames = &Apache::lonlocal::texthash(
                   3626:             uc   => 'At least one upper case letter',
                   3627:             lc   => 'At least one lower case letter',
                   3628:             num  => 'At least one number',
                   3629:             spec => 'At least one non-alphanumeric',
                   3630:         );
                   3631:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3632:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3633:         $rulenames{'num'} .= ': 0123456789';
                   3634:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3635:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3636:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3637:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3638:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3639:             if (grep(/^$rule$/,@brokerule)) {
                   3640:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3641:             }
                   3642:         }
                   3643:         $warning .= '</ul>';
                   3644:     }
1.1332    raeburn  3645:     if (wantarray) {
                   3646:         return @brokerule;
                   3647:     }
1.1331    raeburn  3648:     return $warning;
                   3649: }
                   3650: 
1.80      albertel 3651: ###############################################################
                   3652: ##    Get Kerberos Defaults for Domain                 ##
                   3653: ###############################################################
                   3654: ##
                   3655: ## Returns default kerberos version and an associated argument
                   3656: ## as listed in file domain.tab. If not listed, provides
                   3657: ## appropriate default domain and kerberos version.
                   3658: ##
                   3659: #-------------------------------------------
                   3660: 
                   3661: =pod
                   3662: 
1.648     raeburn  3663: =item * &get_kerberos_defaults()
1.80      albertel 3664: 
                   3665: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3666: version and domain. If not found, it defaults to version 4 and the 
                   3667: domain of the server.
1.80      albertel 3668: 
1.648     raeburn  3669: =over 4
                   3670: 
1.80      albertel 3671: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3672: 
1.648     raeburn  3673: =back
                   3674: 
                   3675: =back
                   3676: 
1.80      albertel 3677: =cut
                   3678: 
                   3679: #-------------------------------------------
                   3680: sub get_kerberos_defaults {
                   3681:     my $domain=shift;
1.641     raeburn  3682:     my ($krbdef,$krbdefdom);
                   3683:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3684:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3685:         $krbdef = $domdefaults{'auth_def'};
                   3686:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3687:     } else {
1.80      albertel 3688:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3689:         my $krbdefdom=$1;
                   3690:         $krbdefdom=~tr/a-z/A-Z/;
                   3691:         $krbdef = "krb4";
                   3692:     }
                   3693:     return ($krbdef,$krbdefdom);
                   3694: }
1.112     bowersj2 3695: 
1.32      matthew  3696: 
1.46      matthew  3697: ###############################################################
                   3698: ##                Thesaurus Functions                        ##
                   3699: ###############################################################
1.20      www      3700: 
1.46      matthew  3701: =pod
1.20      www      3702: 
1.112     bowersj2 3703: =head1 Thesaurus Functions
                   3704: 
                   3705: =over 4
                   3706: 
1.648     raeburn  3707: =item * &initialize_keywords()
1.46      matthew  3708: 
                   3709: Initializes the package variable %Keywords if it is empty.  Uses the
                   3710: package variable $thesaurus_db_file.
                   3711: 
                   3712: =cut
                   3713: 
                   3714: ###################################################
                   3715: 
                   3716: sub initialize_keywords {
                   3717:     return 1 if (scalar keys(%Keywords));
                   3718:     # If we are here, %Keywords is empty, so fill it up
                   3719:     #   Make sure the file we need exists...
                   3720:     if (! -e $thesaurus_db_file) {
                   3721:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3722:                                  " failed because it does not exist");
                   3723:         return 0;
                   3724:     }
                   3725:     #   Set up the hash as a database
                   3726:     my %thesaurus_db;
                   3727:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3728:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3729:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3730:                                  $thesaurus_db_file);
                   3731:         return 0;
                   3732:     } 
                   3733:     #  Get the average number of appearances of a word.
                   3734:     my $avecount = $thesaurus_db{'average.count'};
                   3735:     #  Put keywords (those that appear > average) into %Keywords
                   3736:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3737:         my ($count,undef) = split /:/,$data;
                   3738:         $Keywords{$word}++ if ($count > $avecount);
                   3739:     }
                   3740:     untie %thesaurus_db;
                   3741:     # Remove special values from %Keywords.
1.356     albertel 3742:     foreach my $value ('total.count','average.count') {
                   3743:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3744:   }
1.46      matthew  3745:     return 1;
                   3746: }
                   3747: 
                   3748: ###################################################
                   3749: 
                   3750: =pod
                   3751: 
1.648     raeburn  3752: =item * &keyword($word)
1.46      matthew  3753: 
                   3754: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3755: than the average number of times in the thesaurus database.  Calls 
                   3756: &initialize_keywords
                   3757: 
                   3758: =cut
                   3759: 
                   3760: ###################################################
1.20      www      3761: 
                   3762: sub keyword {
1.46      matthew  3763:     return if (!&initialize_keywords());
                   3764:     my $word=lc(shift());
                   3765:     $word=~s/\W//g;
                   3766:     return exists($Keywords{$word});
1.20      www      3767: }
1.46      matthew  3768: 
                   3769: ###############################################################
                   3770: 
                   3771: =pod 
1.20      www      3772: 
1.648     raeburn  3773: =item * &get_related_words()
1.46      matthew  3774: 
1.160     matthew  3775: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3776: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3777: will be returned.  The order of the words returned is determined by the
                   3778: database which holds them.
                   3779: 
                   3780: Uses global $thesaurus_db_file.
                   3781: 
1.1057    foxr     3782: 
1.46      matthew  3783: =cut
                   3784: 
                   3785: ###############################################################
                   3786: sub get_related_words {
                   3787:     my $keyword = shift;
                   3788:     my %thesaurus_db;
                   3789:     if (! -e $thesaurus_db_file) {
                   3790:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3791:                                  "failed because the file does not exist");
                   3792:         return ();
                   3793:     }
                   3794:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3795:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3796:         return ();
                   3797:     } 
                   3798:     my @Words=();
1.429     www      3799:     my $count=0;
1.46      matthew  3800:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3801: 	# The first element is the number of times
                   3802: 	# the word appears.  We do not need it now.
1.429     www      3803: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3804: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3805: 	my $threshold=$mostfrequentcount/10;
                   3806:         foreach my $possibleword (@RelatedWords) {
                   3807:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3808:             if ($wordcount>$threshold) {
                   3809: 		push(@Words,$word);
                   3810:                 $count++;
                   3811:                 if ($count>10) { last; }
                   3812: 	    }
1.20      www      3813:         }
                   3814:     }
1.46      matthew  3815:     untie %thesaurus_db;
                   3816:     return @Words;
1.14      harris41 3817: }
1.1090    foxr     3818: ###############################################################
                   3819: #
                   3820: #  Spell checking
                   3821: #
                   3822: 
                   3823: =pod
                   3824: 
1.1142    raeburn  3825: =back
                   3826: 
1.1090    foxr     3827: =head1 Spell checking
                   3828: 
                   3829: =over 4
                   3830: 
                   3831: =item * &check_spelling($wordlist $language)
                   3832: 
                   3833: Takes a string containing words and feeds it to an external
                   3834: spellcheck program via a pipeline. Returns a string containing
                   3835: them mis-spelled words.
                   3836: 
                   3837: Parameters:
                   3838: 
                   3839: =over 4
                   3840: 
                   3841: =item - $wordlist
                   3842: 
                   3843: String that will be fed into the spellcheck program.
                   3844: 
                   3845: =item - $language
                   3846: 
                   3847: Language string that specifies the language for which the spell
                   3848: check will be performed.
                   3849: 
                   3850: =back
                   3851: 
                   3852: =back
                   3853: 
                   3854: Note: This sub assumes that aspell is installed.
                   3855: 
                   3856: 
                   3857: =cut
                   3858: 
1.46      matthew  3859: 
1.1090    foxr     3860: sub check_spelling {
                   3861:     my ($wordlist, $language) = @_;
1.1091    foxr     3862:     my @misspellings;
                   3863:     
                   3864:     # Generate the speller and set the langauge.
                   3865:     # if explicitly selected:
1.1090    foxr     3866: 
1.1091    foxr     3867:     my $speller = Text::Aspell->new;
1.1090    foxr     3868:     if ($language) {
1.1091    foxr     3869: 	$speller->set_option('lang', $language);
1.1090    foxr     3870:     }
                   3871: 
1.1091    foxr     3872:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3873: 
1.1091    foxr     3874:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3875: 
1.1091    foxr     3876:     foreach my $word (@words) {
                   3877: 	if(! $speller->check($word)) {
                   3878: 	    push(@misspellings, $word);
1.1090    foxr     3879: 	}
                   3880:     }
1.1091    foxr     3881:     return join(' ', @misspellings);
                   3882:     
1.1090    foxr     3883: }
                   3884: 
1.61      www      3885: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3886: =pod
                   3887: 
1.112     bowersj2 3888: =head1 User Name Functions
                   3889: 
                   3890: =over 4
                   3891: 
1.648     raeburn  3892: =item * &plainname($uname,$udom,$first)
1.81      albertel 3893: 
1.112     bowersj2 3894: Takes a users logon name and returns it as a string in
1.226     albertel 3895: "first middle last generation" form 
                   3896: if $first is set to 'lastname' then it returns it as
                   3897: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3898: 
                   3899: =cut
1.61      www      3900: 
1.295     www      3901: 
1.81      albertel 3902: ###############################################################
1.61      www      3903: sub plainname {
1.226     albertel 3904:     my ($uname,$udom,$first)=@_;
1.537     albertel 3905:     return if (!defined($uname) || !defined($udom));
1.295     www      3906:     my %names=&getnames($uname,$udom);
1.226     albertel 3907:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3908: 					  $names{'middlename'},
                   3909: 					  $names{'lastname'},
                   3910: 					  $names{'generation'},$first);
                   3911:     $name=~s/^\s+//;
1.62      www      3912:     $name=~s/\s+$//;
                   3913:     $name=~s/\s+/ /g;
1.353     albertel 3914:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3915:     return $name;
1.61      www      3916: }
1.66      www      3917: 
                   3918: # -------------------------------------------------------------------- Nickname
1.81      albertel 3919: =pod
                   3920: 
1.648     raeburn  3921: =item * &nickname($uname,$udom)
1.81      albertel 3922: 
                   3923: Gets a users name and returns it as a string as
                   3924: 
                   3925: "&quot;nickname&quot;"
1.66      www      3926: 
1.81      albertel 3927: if the user has a nickname or
                   3928: 
                   3929: "first middle last generation"
                   3930: 
                   3931: if the user does not
                   3932: 
                   3933: =cut
1.66      www      3934: 
                   3935: sub nickname {
                   3936:     my ($uname,$udom)=@_;
1.537     albertel 3937:     return if (!defined($uname) || !defined($udom));
1.295     www      3938:     my %names=&getnames($uname,$udom);
1.68      albertel 3939:     my $name=$names{'nickname'};
1.66      www      3940:     if ($name) {
                   3941:        $name='&quot;'.$name.'&quot;'; 
                   3942:     } else {
                   3943:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3944: 	     $names{'lastname'}.' '.$names{'generation'};
                   3945:        $name=~s/\s+$//;
                   3946:        $name=~s/\s+/ /g;
                   3947:     }
                   3948:     return $name;
                   3949: }
                   3950: 
1.295     www      3951: sub getnames {
                   3952:     my ($uname,$udom)=@_;
1.537     albertel 3953:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3954:     if ($udom eq 'public' && $uname eq 'public') {
                   3955: 	return ('lastname' => &mt('Public'));
                   3956:     }
1.295     www      3957:     my $id=$uname.':'.$udom;
                   3958:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3959:     if ($cached) {
                   3960: 	return %{$names};
                   3961:     } else {
                   3962: 	my %loadnames=&Apache::lonnet::get('environment',
                   3963:                     ['firstname','middlename','lastname','generation','nickname'],
                   3964: 					 $udom,$uname);
                   3965: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3966: 	return %loadnames;
                   3967:     }
                   3968: }
1.61      www      3969: 
1.542     raeburn  3970: # -------------------------------------------------------------------- getemails
1.648     raeburn  3971: 
1.542     raeburn  3972: =pod
                   3973: 
1.648     raeburn  3974: =item * &getemails($uname,$udom)
1.542     raeburn  3975: 
                   3976: Gets a user's email information and returns it as a hash with keys:
                   3977: notification, critnotification, permanentemail
                   3978: 
                   3979: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3980: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3981:  
1.648     raeburn  3982: 
1.542     raeburn  3983: =cut
                   3984: 
1.648     raeburn  3985: 
1.466     albertel 3986: sub getemails {
                   3987:     my ($uname,$udom)=@_;
                   3988:     if ($udom eq 'public' && $uname eq 'public') {
                   3989: 	return;
                   3990:     }
1.467     www      3991:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3992:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3993:     my $id=$uname.':'.$udom;
                   3994:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3995:     if ($cached) {
                   3996: 	return %{$names};
                   3997:     } else {
                   3998: 	my %loadnames=&Apache::lonnet::get('environment',
                   3999:                     			   ['notification','critnotification',
                   4000: 					    'permanentemail'],
                   4001: 					   $udom,$uname);
                   4002: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4003: 	return %loadnames;
                   4004:     }
                   4005: }
                   4006: 
1.551     albertel 4007: sub flush_email_cache {
                   4008:     my ($uname,$udom)=@_;
                   4009:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4010:     if (!$uname) { $uname=$env{'user.name'};   }
                   4011:     return if ($udom eq 'public' && $uname eq 'public');
                   4012:     my $id=$uname.':'.$udom;
                   4013:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4014: }
                   4015: 
1.728     raeburn  4016: # -------------------------------------------------------------------- getlangs
                   4017: 
                   4018: =pod
                   4019: 
                   4020: =item * &getlangs($uname,$udom)
                   4021: 
                   4022: Gets a user's language preference and returns it as a hash with key:
                   4023: language.
                   4024: 
                   4025: =cut
                   4026: 
                   4027: 
                   4028: sub getlangs {
                   4029:     my ($uname,$udom) = @_;
                   4030:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4031:     if (!$uname) { $uname=$env{'user.name'};   }
                   4032:     my $id=$uname.':'.$udom;
                   4033:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4034:     if ($cached) {
                   4035:         return %{$langs};
                   4036:     } else {
                   4037:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4038:                                            $udom,$uname);
                   4039:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4040:         return %loadlangs;
                   4041:     }
                   4042: }
                   4043: 
                   4044: sub flush_langs_cache {
                   4045:     my ($uname,$udom)=@_;
                   4046:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4047:     if (!$uname) { $uname=$env{'user.name'};   }
                   4048:     return if ($udom eq 'public' && $uname eq 'public');
                   4049:     my $id=$uname.':'.$udom;
                   4050:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4051: }
                   4052: 
1.61      www      4053: # ------------------------------------------------------------------ Screenname
1.81      albertel 4054: 
                   4055: =pod
                   4056: 
1.648     raeburn  4057: =item * &screenname($uname,$udom)
1.81      albertel 4058: 
                   4059: Gets a users screenname and returns it as a string
                   4060: 
                   4061: =cut
1.61      www      4062: 
                   4063: sub screenname {
                   4064:     my ($uname,$udom)=@_;
1.258     albertel 4065:     if ($uname eq $env{'user.name'} &&
                   4066: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4067:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4068:     return $names{'screenname'};
1.62      www      4069: }
                   4070: 
1.212     albertel 4071: 
1.802     bisitz   4072: # ------------------------------------------------------------- Confirm Wrapper
                   4073: =pod
                   4074: 
1.1142    raeburn  4075: =item * &confirmwrapper($message)
1.802     bisitz   4076: 
                   4077: Wrap messages about completion of operation in box
                   4078: 
                   4079: =cut
                   4080: 
                   4081: sub confirmwrapper {
                   4082:     my ($message)=@_;
                   4083:     if ($message) {
                   4084:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4085:                .$message."\n"
                   4086:                .'</div>'."\n";
                   4087:     } else {
                   4088:         return $message;
                   4089:     }
                   4090: }
                   4091: 
1.62      www      4092: # ------------------------------------------------------------- Message Wrapper
                   4093: 
                   4094: sub messagewrapper {
1.369     www      4095:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4096:     return 
1.441     albertel 4097:         '<a href="/adm/email?compose=individual&amp;'.
                   4098:         'recname='.$username.'&amp;recdom='.$domain.
                   4099: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4100:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4101: }
1.802     bisitz   4102: 
1.74      www      4103: # --------------------------------------------------------------- Notes Wrapper
                   4104: 
                   4105: sub noteswrapper {
                   4106:     my ($link,$un,$do)=@_;
                   4107:     return 
1.896     amueller 4108: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4109: }
1.802     bisitz   4110: 
1.62      www      4111: # ------------------------------------------------------------- Aboutme Wrapper
                   4112: 
                   4113: sub aboutmewrapper {
1.1070    raeburn  4114:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4115:     if (!defined($username)  && !defined($domain)) {
                   4116:         return;
                   4117:     }
1.1096    raeburn  4118:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4119: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4120: }
                   4121: 
                   4122: # ------------------------------------------------------------ Syllabus Wrapper
                   4123: 
                   4124: sub syllabuswrapper {
1.707     bisitz   4125:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4126:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4127: }
1.14      harris41 4128: 
1.802     bisitz   4129: # -----------------------------------------------------------------------------
                   4130: 
1.208     matthew  4131: sub track_student_link {
1.887     raeburn  4132:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4133:     my $link ="/adm/trackstudent?";
1.208     matthew  4134:     my $title = 'View recent activity';
                   4135:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4136:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4137:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4138:         $title .= ' of this student';
1.268     albertel 4139:     } 
1.208     matthew  4140:     if (defined($target) && $target !~ /^\s*$/) {
                   4141:         $target = qq{target="$target"};
                   4142:     } else {
                   4143:         $target = '';
                   4144:     }
1.268     albertel 4145:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4146:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4147:     $title = &mt($title);
                   4148:     $linktext = &mt($linktext);
1.448     albertel 4149:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4150: 	&help_open_topic('View_recent_activity');
1.208     matthew  4151: }
                   4152: 
1.781     raeburn  4153: sub slot_reservations_link {
                   4154:     my ($linktext,$sname,$sdom,$target) = @_;
                   4155:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4156:     my $title = 'View slot reservation history';
                   4157:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4158:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4159:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4160:         $title .= ' of this student';
                   4161:     }
                   4162:     if (defined($target) && $target !~ /^\s*$/) {
                   4163:         $target = qq{target="$target"};
                   4164:     } else {
                   4165:         $target = '';
                   4166:     }
                   4167:     $title = &mt($title);
                   4168:     $linktext = &mt($linktext);
                   4169:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4170: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4171: 
                   4172: }
                   4173: 
1.508     www      4174: # ===================================================== Display a student photo
                   4175: 
                   4176: 
1.509     albertel 4177: sub student_image_tag {
1.508     www      4178:     my ($domain,$user)=@_;
                   4179:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4180:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4181: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4182:     } else {
                   4183: 	return '';
                   4184:     }
                   4185: }
                   4186: 
1.112     bowersj2 4187: =pod
                   4188: 
                   4189: =back
                   4190: 
                   4191: =head1 Access .tab File Data
                   4192: 
                   4193: =over 4
                   4194: 
1.648     raeburn  4195: =item * &languageids() 
1.112     bowersj2 4196: 
                   4197: returns list of all language ids
                   4198: 
                   4199: =cut
                   4200: 
1.14      harris41 4201: sub languageids {
1.16      harris41 4202:     return sort(keys(%language));
1.14      harris41 4203: }
                   4204: 
1.112     bowersj2 4205: =pod
                   4206: 
1.648     raeburn  4207: =item * &languagedescription() 
1.112     bowersj2 4208: 
                   4209: returns description of a specified language id
                   4210: 
                   4211: =cut
                   4212: 
1.14      harris41 4213: sub languagedescription {
1.125     www      4214:     my $code=shift;
                   4215:     return  ($supported_language{$code}?'* ':'').
                   4216:             $language{$code}.
1.126     www      4217: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4218: }
                   4219: 
1.1048    foxr     4220: =pod
                   4221: 
                   4222: =item * &plainlanguagedescription
                   4223: 
                   4224: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4225: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4226: 
                   4227: =cut
                   4228: 
1.145     www      4229: sub plainlanguagedescription {
                   4230:     my $code=shift;
                   4231:     return $language{$code};
                   4232: }
                   4233: 
1.1048    foxr     4234: =pod
                   4235: 
                   4236: =item * &supportedlanguagecode
                   4237: 
                   4238: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4239: code.
                   4240: 
                   4241: =cut
                   4242: 
1.145     www      4243: sub supportedlanguagecode {
                   4244:     my $code=shift;
                   4245:     return $supported_language{$code};
1.97      www      4246: }
                   4247: 
1.112     bowersj2 4248: =pod
                   4249: 
1.1048    foxr     4250: =item * &latexlanguage()
                   4251: 
                   4252: Given a language key code returns the correspondnig language to use
                   4253: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4254: is no supported hyphenation for the language code.
                   4255: 
                   4256: =cut
                   4257: 
                   4258: sub latexlanguage {
                   4259:     my $code = shift;
                   4260:     return $latex_language{$code};
                   4261: }
                   4262: 
                   4263: =pod
                   4264: 
                   4265: =item * &latexhyphenation()
                   4266: 
                   4267: Same as above but what's supplied is the language as it might be stored
                   4268: in the metadata.
                   4269: 
                   4270: =cut
                   4271: 
                   4272: sub latexhyphenation {
                   4273:     my $key = shift;
                   4274:     return $latex_language_bykey{$key};
                   4275: }
                   4276: 
                   4277: =pod
                   4278: 
1.648     raeburn  4279: =item * &copyrightids() 
1.112     bowersj2 4280: 
                   4281: returns list of all copyrights
                   4282: 
                   4283: =cut
                   4284: 
                   4285: sub copyrightids {
                   4286:     return sort(keys(%cprtag));
                   4287: }
                   4288: 
                   4289: =pod
                   4290: 
1.648     raeburn  4291: =item * &copyrightdescription() 
1.112     bowersj2 4292: 
                   4293: returns description of a specified copyright id
                   4294: 
                   4295: =cut
                   4296: 
                   4297: sub copyrightdescription {
1.166     www      4298:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4299: }
1.197     matthew  4300: 
                   4301: =pod
                   4302: 
1.648     raeburn  4303: =item * &source_copyrightids() 
1.192     taceyjo1 4304: 
                   4305: returns list of all source copyrights
                   4306: 
                   4307: =cut
                   4308: 
                   4309: sub source_copyrightids {
                   4310:     return sort(keys(%scprtag));
                   4311: }
                   4312: 
                   4313: =pod
                   4314: 
1.648     raeburn  4315: =item * &source_copyrightdescription() 
1.192     taceyjo1 4316: 
                   4317: returns description of a specified source copyright id
                   4318: 
                   4319: =cut
                   4320: 
                   4321: sub source_copyrightdescription {
                   4322:     return &mt($scprtag{shift(@_)});
                   4323: }
1.112     bowersj2 4324: 
                   4325: =pod
                   4326: 
1.648     raeburn  4327: =item * &filecategories() 
1.112     bowersj2 4328: 
                   4329: returns list of all file categories
                   4330: 
                   4331: =cut
                   4332: 
                   4333: sub filecategories {
                   4334:     return sort(keys(%category_extensions));
                   4335: }
                   4336: 
                   4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &filecategorytypes() 
1.112     bowersj2 4340: 
                   4341: returns list of file types belonging to a given file
                   4342: category
                   4343: 
                   4344: =cut
                   4345: 
                   4346: sub filecategorytypes {
1.356     albertel 4347:     my ($cat) = @_;
1.1248    raeburn  4348:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4349:         return @{$category_extensions{lc($cat)}};
                   4350:     } else {
                   4351:         return ();
                   4352:     }
1.112     bowersj2 4353: }
                   4354: 
                   4355: =pod
                   4356: 
1.648     raeburn  4357: =item * &fileembstyle() 
1.112     bowersj2 4358: 
                   4359: returns embedding style for a specified file type
                   4360: 
                   4361: =cut
                   4362: 
                   4363: sub fileembstyle {
                   4364:     return $fe{lc(shift(@_))};
1.169     www      4365: }
                   4366: 
1.351     www      4367: sub filemimetype {
                   4368:     return $fm{lc(shift(@_))};
                   4369: }
                   4370: 
1.169     www      4371: 
                   4372: sub filecategoryselect {
                   4373:     my ($name,$value)=@_;
1.189     matthew  4374:     return &select_form($value,$name,
1.970     raeburn  4375:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4376: }
                   4377: 
                   4378: =pod
                   4379: 
1.648     raeburn  4380: =item * &filedescription() 
1.112     bowersj2 4381: 
                   4382: returns description for a specified file type
                   4383: 
                   4384: =cut
                   4385: 
                   4386: sub filedescription {
1.188     matthew  4387:     my $file_description = $fd{lc(shift())};
                   4388:     $file_description =~ s:([\[\]]):~$1:g;
                   4389:     return &mt($file_description);
1.112     bowersj2 4390: }
                   4391: 
                   4392: =pod
                   4393: 
1.648     raeburn  4394: =item * &filedescriptionex() 
1.112     bowersj2 4395: 
                   4396: returns description for a specified file type with
                   4397: extra formatting
                   4398: 
                   4399: =cut
                   4400: 
                   4401: sub filedescriptionex {
                   4402:     my $ex=shift;
1.188     matthew  4403:     my $file_description = $fd{lc($ex)};
                   4404:     $file_description =~ s:([\[\]]):~$1:g;
                   4405:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4406: }
                   4407: 
                   4408: # End of .tab access
                   4409: =pod
                   4410: 
                   4411: =back
                   4412: 
                   4413: =cut
                   4414: 
                   4415: # ------------------------------------------------------------------ File Types
                   4416: sub fileextensions {
                   4417:     return sort(keys(%fe));
                   4418: }
                   4419: 
1.97      www      4420: # ----------------------------------------------------------- Display Languages
                   4421: # returns a hash with all desired display languages
                   4422: #
                   4423: 
                   4424: sub display_languages {
                   4425:     my %languages=();
1.695     raeburn  4426:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4427: 	$languages{$lang}=1;
1.97      www      4428:     }
                   4429:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4430:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4431: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4432: 	    $languages{$lang}=1;
1.97      www      4433:         }
                   4434:     }
                   4435:     return %languages;
1.14      harris41 4436: }
                   4437: 
1.582     albertel 4438: sub languages {
                   4439:     my ($possible_langs) = @_;
1.695     raeburn  4440:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4441:     if (!ref($possible_langs)) {
                   4442: 	if( wantarray ) {
                   4443: 	    return @preferred_langs;
                   4444: 	} else {
                   4445: 	    return $preferred_langs[0];
                   4446: 	}
                   4447:     }
                   4448:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4449:     my @preferred_possibilities;
                   4450:     foreach my $preferred_lang (@preferred_langs) {
                   4451: 	if (exists($possibilities{$preferred_lang})) {
                   4452: 	    push(@preferred_possibilities, $preferred_lang);
                   4453: 	}
                   4454:     }
                   4455:     if( wantarray ) {
                   4456: 	return @preferred_possibilities;
                   4457:     }
                   4458:     return $preferred_possibilities[0];
                   4459: }
                   4460: 
1.742     raeburn  4461: sub user_lang {
                   4462:     my ($touname,$toudom,$fromcid) = @_;
                   4463:     my @userlangs;
                   4464:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4465:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4466:                     $env{'course.'.$fromcid.'.languages'}));
                   4467:     } else {
                   4468:         my %langhash = &getlangs($touname,$toudom);
                   4469:         if ($langhash{'languages'} ne '') {
                   4470:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4471:         } else {
                   4472:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4473:             if ($domdefs{'lang_def'} ne '') {
                   4474:                 @userlangs = ($domdefs{'lang_def'});
                   4475:             }
                   4476:         }
                   4477:     }
                   4478:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4479:     my $user_lh = Apache::localize->get_handle(@languages);
                   4480:     return $user_lh;
                   4481: }
                   4482: 
                   4483: 
1.112     bowersj2 4484: ###############################################################
                   4485: ##               Student Answer Attempts                     ##
                   4486: ###############################################################
                   4487: 
                   4488: =pod
                   4489: 
                   4490: =head1 Alternate Problem Views
                   4491: 
                   4492: =over 4
                   4493: 
1.648     raeburn  4494: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4495:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4496: 
                   4497: Return string with previous attempt on problem. Arguments:
                   4498: 
                   4499: =over 4
                   4500: 
                   4501: =item * $symb: Problem, including path
                   4502: 
                   4503: =item * $username: username of the desired student
                   4504: 
                   4505: =item * $domain: domain of the desired student
1.14      harris41 4506: 
1.112     bowersj2 4507: =item * $course: Course ID
1.14      harris41 4508: 
1.112     bowersj2 4509: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4510:     something
1.14      harris41 4511: 
1.112     bowersj2 4512: =item * $regexp: if string matches this regexp, the string will be
                   4513:     sent to $gradesub
1.14      harris41 4514: 
1.112     bowersj2 4515: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4516: 
1.1199    raeburn  4517: =item * $usec: section of the desired student
                   4518: 
                   4519: =item * $identifier: counter for student (multiple students one problem) or 
                   4520:     problem (one student; whole sequence).
                   4521: 
1.112     bowersj2 4522: =back
1.14      harris41 4523: 
1.112     bowersj2 4524: The output string is a table containing all desired attempts, if any.
1.16      harris41 4525: 
1.112     bowersj2 4526: =cut
1.1       albertel 4527: 
                   4528: sub get_previous_attempt {
1.1199    raeburn  4529:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4530:   my $prevattempts='';
1.43      ng       4531:   no strict 'refs';
1.1       albertel 4532:   if ($symb) {
1.3       albertel 4533:     my (%returnhash)=
                   4534:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4535:     if ($returnhash{'version'}) {
                   4536:       my %lasthash=();
                   4537:       my $version;
                   4538:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4539:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4540:             if ($key =~ /\.rawrndseed$/) {
                   4541:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4542:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4543:             } else {
                   4544:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4545:             }
1.19      harris41 4546:         }
1.1       albertel 4547:       }
1.596     albertel 4548:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4549:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4550:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4551:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4552:       foreach my $key (sort(keys(%lasthash))) {
                   4553: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4554: 	if ($#parts > 0) {
1.31      albertel 4555: 	  my $data=$parts[-1];
1.989     raeburn  4556:           next if ($data eq 'foilorder');
1.31      albertel 4557: 	  pop(@parts);
1.1010    www      4558:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4559:           if ($data eq 'type') {
                   4560:               unless ($showsurv) {
                   4561:                   my $id = join(',',@parts);
                   4562:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4563:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4564:                       $lasthidden{$ign.'.'.$id} = 1;
                   4565:                   }
1.945     raeburn  4566:               }
1.1199    raeburn  4567:               if ($identifier ne '') {
                   4568:                   my $id = join(',',@parts);
                   4569:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4570:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4571:                       $hidestatus{$ign.'.'.$id} = 1;
                   4572:                   }
                   4573:               }
                   4574:           } elsif ($data eq 'regrader') {
                   4575:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4576:                   my $id = join(',',@parts);
                   4577:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4578:               }
1.1010    www      4579:           } 
1.31      albertel 4580: 	} else {
1.41      ng       4581: 	  if ($#parts == 0) {
                   4582: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4583: 	  } else {
                   4584: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4585: 	  }
1.31      albertel 4586: 	}
1.16      harris41 4587:       }
1.596     albertel 4588:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4589:       if ($getattempt eq '') {
1.1199    raeburn  4590:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4591:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4592:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4593:                 foreach my $id (keys(%regraded)) {
                   4594:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4595:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4596:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4597:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4598:                     }
                   4599:                 }
                   4600:             }
1.1200    raeburn  4601:         }
                   4602: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4603:             my (@hidden,@unsolved);
1.945     raeburn  4604:             if (%typeparts) {
                   4605:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4606:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4607:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4608:                         push(@hidden,$id);
1.1199    raeburn  4609:                     } elsif ($identifier ne '') {
                   4610:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4611:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4612:                                 ($hidestatus{$id})) {
1.1200    raeburn  4613:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4614:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4615:                                 push(@{$solved{$id}},$version);
                   4616:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4617:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4618:                                 my $skip;
                   4619:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4620:                                     foreach my $reset (@{$resets{$id}}) {
                   4621:                                         if ($reset > $solved{$id}[-1]) {
                   4622:                                             $skip=1;
                   4623:                                             last;
                   4624:                                         }
                   4625:                                     }
                   4626:                                 }
                   4627:                                 unless ($skip) {
                   4628:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4629:                                     push(@unsolved,$partslist);
                   4630:                                 }
                   4631:                             }
                   4632:                         }
1.945     raeburn  4633:                     }
                   4634:                 }
                   4635:             }
                   4636:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4637:                            '<td>'.&mt('Transaction [_1]',$version);
                   4638:             if (@unsolved) {
                   4639:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4640:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4641:                                  &mt('Hide').'</label></span>';
                   4642:             }
                   4643:             $prevattempts .= '</td>';
1.945     raeburn  4644:             if (@hidden) {
                   4645:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4646:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4647:                     my $hide;
                   4648:                     foreach my $id (@hidden) {
                   4649:                         if ($key =~ /^\Q$id\E/) {
                   4650:                             $hide = 1;
                   4651:                             last;
                   4652:                         }
                   4653:                     }
                   4654:                     if ($hide) {
                   4655:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4656:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4657:                             my $value = &format_previous_attempt_value($key,
                   4658:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4659:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4660:                         } else {
                   4661:                             $prevattempts.='<td>&nbsp;</td>';
                   4662:                         }
                   4663:                     } else {
                   4664:                         if ($key =~ /\./) {
1.1212    raeburn  4665:                             my $value = $returnhash{$version.':'.$key};
                   4666:                             if ($key =~ /\.rndseed$/) {
                   4667:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4668:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4669:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4670:                                 }
                   4671:                             }
                   4672:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4673:                                            '&nbsp;</td>';
1.945     raeburn  4674:                         } else {
                   4675:                             $prevattempts.='<td>&nbsp;</td>';
                   4676:                         }
                   4677:                     }
                   4678:                 }
                   4679:             } else {
                   4680: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4681:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4682:                     my $value = $returnhash{$version.':'.$key};
                   4683:                     if ($key =~ /\.rndseed$/) {
                   4684:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4685:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4686:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4687:                         }
                   4688:                     }
                   4689:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4690:                                    '&nbsp;</td>';
1.945     raeburn  4691: 	        }
                   4692:             }
                   4693: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4694: 	 }
1.1       albertel 4695:       }
1.945     raeburn  4696:       my @currhidden = keys(%lasthidden);
1.596     albertel 4697:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4698:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4699:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4700:           if (%typeparts) {
                   4701:               my $hidden;
                   4702:               foreach my $id (@currhidden) {
                   4703:                   if ($key =~ /^\Q$id\E/) {
                   4704:                       $hidden = 1;
                   4705:                       last;
                   4706:                   }
                   4707:               }
                   4708:               if ($hidden) {
                   4709:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4710:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4711:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4712:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4713:                           $value = &$gradesub($value);
                   4714:                       }
1.1173    kruse    4715:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4716:                   } else {
                   4717:                       $prevattempts.='<td>&nbsp;</td>';
                   4718:                   }
                   4719:               } else {
                   4720:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4721:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4722:                       $value = &$gradesub($value);
                   4723:                   }
1.1173    kruse    4724:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4725:               }
                   4726:           } else {
                   4727: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4728: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4729:                   $value = &$gradesub($value);
                   4730:               }
1.1173    kruse    4731: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4732:           }
1.16      harris41 4733:       }
1.596     albertel 4734:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4735:     } else {
1.1305    raeburn  4736:       my $msg;
                   4737:       if ($symb =~ /ext\.tool$/) {
                   4738:           $msg = &mt('No grade passed back.');
                   4739:       } else {
                   4740:           $msg = &mt('Nothing submitted - no attempts.');
                   4741:       }
1.596     albertel 4742:       $prevattempts=
                   4743: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4744: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4745: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4746:     }
                   4747:   } else {
1.596     albertel 4748:     $prevattempts=
                   4749: 	  &start_data_table().&start_data_table_row().
                   4750: 	  '<td>'.&mt('No data.').'</td>'.
                   4751: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4752:   }
1.10      albertel 4753: }
                   4754: 
1.581     albertel 4755: sub format_previous_attempt_value {
                   4756:     my ($key,$value) = @_;
1.1011    www      4757:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4758:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4759:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4760:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4761:     } elsif ($key =~ /answerstring$/) {
                   4762:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4763:         my @answer = %answers;
                   4764:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4765:         my @anskeys = sort(keys(%answers));
                   4766:         if (@anskeys == 1) {
                   4767:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4768:             if ($answer =~ m{\0}) {
                   4769:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4770:             }
                   4771:             my $tag_internal_answer_name = 'INTERNAL';
                   4772:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4773:                 $value = $answer; 
                   4774:             } else {
                   4775:                 $value = $anskeys[0].'='.$answer;
                   4776:             }
                   4777:         } else {
                   4778:             foreach my $ans (@anskeys) {
                   4779:                 my $answer = $answers{$ans};
1.1001    raeburn  4780:                 if ($answer =~ m{\0}) {
                   4781:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4782:                 }
                   4783:                 $value .=  $ans.'='.$answer.'<br />';;
                   4784:             } 
                   4785:         }
1.581     albertel 4786:     } else {
1.1173    kruse    4787:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4788:     }
                   4789:     return $value;
                   4790: }
                   4791: 
                   4792: 
1.107     albertel 4793: sub relative_to_absolute {
                   4794:     my ($url,$output)=@_;
                   4795:     my $parser=HTML::TokeParser->new(\$output);
                   4796:     my $token;
                   4797:     my $thisdir=$url;
                   4798:     my @rlinks=();
                   4799:     while ($token=$parser->get_token) {
                   4800: 	if ($token->[0] eq 'S') {
                   4801: 	    if ($token->[1] eq 'a') {
                   4802: 		if ($token->[2]->{'href'}) {
                   4803: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4804: 		}
                   4805: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4806: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4807: 	    } elsif ($token->[1] eq 'base') {
                   4808: 		$thisdir=$token->[2]->{'href'};
                   4809: 	    }
                   4810: 	}
                   4811:     }
                   4812:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4813:     foreach my $link (@rlinks) {
1.726     raeburn  4814: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4815: 		($link=~/^\//) ||
                   4816: 		($link=~/^javascript:/i) ||
                   4817: 		($link=~/^mailto:/i) ||
                   4818: 		($link=~/^\#/)) {
                   4819: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4820: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4821: 	}
                   4822:     }
                   4823: # -------------------------------------------------- Deal with Applet codebases
                   4824:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4825:     return $output;
                   4826: }
                   4827: 
1.112     bowersj2 4828: =pod
                   4829: 
1.648     raeburn  4830: =item * &get_student_view()
1.112     bowersj2 4831: 
                   4832: show a snapshot of what student was looking at
                   4833: 
                   4834: =cut
                   4835: 
1.10      albertel 4836: sub get_student_view {
1.186     albertel 4837:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4838:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4839:   my (%form);
1.10      albertel 4840:   my @elements=('symb','courseid','domain','username');
                   4841:   foreach my $element (@elements) {
1.186     albertel 4842:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4843:   }
1.186     albertel 4844:   if (defined($moreenv)) {
                   4845:       %form=(%form,%{$moreenv});
                   4846:   }
1.236     albertel 4847:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4848:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4849:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4850:       $feedurl =~ s{^/adm/wrapper}{};
                   4851:   }
1.650     www      4852:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4853:   $userview=~s/\<body[^\>]*\>//gi;
                   4854:   $userview=~s/\<\/body\>//gi;
                   4855:   $userview=~s/\<html\>//gi;
                   4856:   $userview=~s/\<\/html\>//gi;
                   4857:   $userview=~s/\<head\>//gi;
                   4858:   $userview=~s/\<\/head\>//gi;
                   4859:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4860:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4861:   if (wantarray) {
                   4862:      return ($userview,$response);
                   4863:   } else {
                   4864:      return $userview;
                   4865:   }
                   4866: }
                   4867: 
                   4868: sub get_student_view_with_retries {
                   4869:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4870: 
                   4871:     my $ok = 0;                 # True if we got a good response.
                   4872:     my $content;
                   4873:     my $response;
                   4874: 
                   4875:     # Try to get the student_view done. within the retries count:
                   4876:     
                   4877:     do {
                   4878:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4879:          $ok      = $response->is_success;
                   4880:          if (!$ok) {
                   4881:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4882:          }
                   4883:          $retries--;
                   4884:     } while (!$ok && ($retries > 0));
                   4885:     
                   4886:     if (!$ok) {
                   4887:        $content = '';          # On error return an empty content.
                   4888:     }
1.651     www      4889:     if (wantarray) {
                   4890:        return ($content, $response);
                   4891:     } else {
                   4892:        return $content;
                   4893:     }
1.11      albertel 4894: }
                   4895: 
1.112     bowersj2 4896: =pod
                   4897: 
1.648     raeburn  4898: =item * &get_student_answers() 
1.112     bowersj2 4899: 
                   4900: show a snapshot of how student was answering problem
                   4901: 
                   4902: =cut
                   4903: 
1.11      albertel 4904: sub get_student_answers {
1.100     sakharuk 4905:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4906:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4907:   my (%moreenv);
1.11      albertel 4908:   my @elements=('symb','courseid','domain','username');
                   4909:   foreach my $element (@elements) {
1.186     albertel 4910:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4911:   }
1.186     albertel 4912:   $moreenv{'grade_target'}='answer';
                   4913:   %moreenv=(%form,%moreenv);
1.497     raeburn  4914:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4915:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4916:   return $userview;
1.1       albertel 4917: }
1.116     albertel 4918: 
                   4919: =pod
                   4920: 
                   4921: =item * &submlink()
                   4922: 
1.242     albertel 4923: Inputs: $text $uname $udom $symb $target
1.116     albertel 4924: 
                   4925: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4926: 
                   4927: =cut
                   4928: 
                   4929: ###############################################
                   4930: sub submlink {
1.242     albertel 4931:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4932:     if (!($uname && $udom)) {
                   4933: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4934: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4935: 	if (!$symb) { $symb=$cursymb; }
                   4936:     }
1.254     matthew  4937:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4938:     $symb=&escape($symb);
1.960     bisitz   4939:     if ($target) { $target=" target=\"$target\""; }
                   4940:     return
                   4941:         '<a href="/adm/grades?command=submission'.
                   4942:         '&amp;symb='.$symb.
                   4943:         '&amp;student='.$uname.
                   4944:         '&amp;userdom='.$udom.'"'.
                   4945:         $target.'>'.$text.'</a>';
1.242     albertel 4946: }
                   4947: ##############################################
                   4948: 
                   4949: =pod
                   4950: 
                   4951: =item * &pgrdlink()
                   4952: 
                   4953: Inputs: $text $uname $udom $symb $target
                   4954: 
                   4955: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4956: 
                   4957: =cut
                   4958: 
                   4959: ###############################################
                   4960: sub pgrdlink {
                   4961:     my $link=&submlink(@_);
                   4962:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4963:     return $link;
                   4964: }
                   4965: ##############################################
                   4966: 
                   4967: =pod
                   4968: 
                   4969: =item * &pprmlink()
                   4970: 
                   4971: Inputs: $text $uname $udom $symb $target
                   4972: 
                   4973: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4974: student and a specific resource
1.242     albertel 4975: 
                   4976: =cut
                   4977: 
                   4978: ###############################################
                   4979: sub pprmlink {
                   4980:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4981:     if (!($uname && $udom)) {
                   4982: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4983: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4984: 	if (!$symb) { $symb=$cursymb; }
                   4985:     }
1.254     matthew  4986:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4987:     $symb=&escape($symb);
1.242     albertel 4988:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4989:     return '<a href="/adm/parmset?command=set&amp;'.
                   4990: 	'symb='.$symb.'&amp;uname='.$uname.
                   4991: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4992: }
                   4993: ##############################################
1.37      matthew  4994: 
1.112     bowersj2 4995: =pod
                   4996: 
                   4997: =back
                   4998: 
                   4999: =cut
                   5000: 
1.37      matthew  5001: ###############################################
1.51      www      5002: 
                   5003: 
                   5004: sub timehash {
1.687     raeburn  5005:     my ($thistime) = @_;
                   5006:     my $timezone = &Apache::lonlocal::gettimezone();
                   5007:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5008:                      ->set_time_zone($timezone);
                   5009:     my $wday = $dt->day_of_week();
                   5010:     if ($wday == 7) { $wday = 0; }
                   5011:     return ( 'second' => $dt->second(),
                   5012:              'minute' => $dt->minute(),
                   5013:              'hour'   => $dt->hour(),
                   5014:              'day'     => $dt->day_of_month(),
                   5015:              'month'   => $dt->month(),
                   5016:              'year'    => $dt->year(),
                   5017:              'weekday' => $wday,
                   5018:              'dayyear' => $dt->day_of_year(),
                   5019:              'dlsav'   => $dt->is_dst() );
1.51      www      5020: }
                   5021: 
1.370     www      5022: sub utc_string {
                   5023:     my ($date)=@_;
1.371     www      5024:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5025: }
                   5026: 
1.51      www      5027: sub maketime {
                   5028:     my %th=@_;
1.687     raeburn  5029:     my ($epoch_time,$timezone,$dt);
                   5030:     $timezone = &Apache::lonlocal::gettimezone();
                   5031:     eval {
                   5032:         $dt = DateTime->new( year   => $th{'year'},
                   5033:                              month  => $th{'month'},
                   5034:                              day    => $th{'day'},
                   5035:                              hour   => $th{'hour'},
                   5036:                              minute => $th{'minute'},
                   5037:                              second => $th{'second'},
                   5038:                              time_zone => $timezone,
                   5039:                          );
                   5040:     };
                   5041:     if (!$@) {
                   5042:         $epoch_time = $dt->epoch;
                   5043:         if ($epoch_time) {
                   5044:             return $epoch_time;
                   5045:         }
                   5046:     }
1.51      www      5047:     return POSIX::mktime(
                   5048:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5049:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5050: }
                   5051: 
                   5052: #########################################
1.51      www      5053: 
                   5054: sub findallcourses {
1.482     raeburn  5055:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5056:     my %roles;
                   5057:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5058:     my %courses;
1.51      www      5059:     my $now=time;
1.482     raeburn  5060:     if (!defined($uname)) {
                   5061:         $uname = $env{'user.name'};
                   5062:     }
                   5063:     if (!defined($udom)) {
                   5064:         $udom = $env{'user.domain'};
                   5065:     }
                   5066:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5067:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5068:         if (!%roles) {
                   5069:             %roles = (
                   5070:                        cc => 1,
1.907     raeburn  5071:                        co => 1,
1.482     raeburn  5072:                        in => 1,
                   5073:                        ep => 1,
                   5074:                        ta => 1,
                   5075:                        cr => 1,
                   5076:                        st => 1,
                   5077:              );
                   5078:         }
                   5079:         foreach my $entry (keys(%roleshash)) {
                   5080:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5081:             if ($trole =~ /^cr/) { 
                   5082:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5083:             } else {
                   5084:                 next if (!exists($roles{$trole}));
                   5085:             }
                   5086:             if ($tend) {
                   5087:                 next if ($tend < $now);
                   5088:             }
                   5089:             if ($tstart) {
                   5090:                 next if ($tstart > $now);
                   5091:             }
1.1058    raeburn  5092:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5093:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5094:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5095:             if ($secpart eq '') {
                   5096:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5097:                 $sec = 'none';
1.1058    raeburn  5098:                 $value .= $cnum.'/';
1.482     raeburn  5099:             } else {
                   5100:                 $cnum = $cnumpart;
                   5101:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5102:                 $value .= $cnum.'/'.$sec;
                   5103:             }
                   5104:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5105:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5106:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5107:                 }
                   5108:             } else {
                   5109:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5110:             }
1.482     raeburn  5111:         }
                   5112:     } else {
                   5113:         foreach my $key (keys(%env)) {
1.483     albertel 5114: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5115:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5116: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5117: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5118: 	        next if (%roles && !exists($roles{$role}));
                   5119: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5120:                 my $active=1;
                   5121:                 if ($starttime) {
                   5122: 		    if ($now<$starttime) { $active=0; }
                   5123:                 }
                   5124:                 if ($endtime) {
                   5125:                     if ($now>$endtime) { $active=0; }
                   5126:                 }
                   5127:                 if ($active) {
1.1058    raeburn  5128:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5129:                     if ($sec eq '') {
                   5130:                         $sec = 'none';
1.1058    raeburn  5131:                     } else {
                   5132:                         $value .= $sec;
                   5133:                     }
                   5134:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5135:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5136:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5137:                         }
                   5138:                     } else {
                   5139:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5140:                     }
1.474     raeburn  5141:                 }
                   5142:             }
1.51      www      5143:         }
                   5144:     }
1.474     raeburn  5145:     return %courses;
1.51      www      5146: }
1.37      matthew  5147: 
1.54      www      5148: ###############################################
1.474     raeburn  5149: 
                   5150: sub blockcheck {
1.1189    raeburn  5151:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  5152: 
1.1189    raeburn  5153:     if (defined($udom) && defined($uname)) {
                   5154:         # If uname and udom are for a course, check for blocks in the course.
                   5155:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5156:             my ($startblock,$endblock,$triggerblock) =
                   5157:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   5158:             return ($startblock,$endblock,$triggerblock);
                   5159:         }
                   5160:     } else {
1.490     raeburn  5161:         $udom = $env{'user.domain'};
                   5162:         $uname = $env{'user.name'};
                   5163:     }
                   5164: 
1.502     raeburn  5165:     my $startblock = 0;
                   5166:     my $endblock = 0;
1.1062    raeburn  5167:     my $triggerblock = '';
1.482     raeburn  5168:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5169: 
1.490     raeburn  5170:     # If uname is for a user, and activity is course-specific, i.e.,
                   5171:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5172: 
1.490     raeburn  5173:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5174:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346  ! raeburn  5175:          $activity eq 'search' || $activity eq 'reinit' ||
        !          5176:          $activity eq 'alert') &&
1.1189    raeburn  5177:         ($env{'request.course.id'})) {
1.490     raeburn  5178:         foreach my $key (keys(%live_courses)) {
                   5179:             if ($key ne $env{'request.course.id'}) {
                   5180:                 delete($live_courses{$key});
                   5181:             }
                   5182:         }
                   5183:     }
                   5184: 
                   5185:     my $otheruser = 0;
                   5186:     my %own_courses;
                   5187:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5188:         # Resource belongs to user other than current user.
                   5189:         $otheruser = 1;
                   5190:         # Gather courses for current user
                   5191:         %own_courses = 
                   5192:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5193:     }
                   5194: 
                   5195:     # Gather active course roles - course coordinator, instructor, 
                   5196:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5197: 
                   5198:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5199:         my ($cdom,$cnum);
                   5200:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5201:             $cdom = $env{'course.'.$course.'.domain'};
                   5202:             $cnum = $env{'course.'.$course.'.num'};
                   5203:         } else {
1.490     raeburn  5204:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5205:         }
                   5206:         my $no_ownblock = 0;
                   5207:         my $no_userblock = 0;
1.533     raeburn  5208:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5209:             # Check if current user has 'evb' priv for this
                   5210:             if (defined($own_courses{$course})) {
                   5211:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5212:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5213:                     if ($sec ne 'none') {
                   5214:                         $checkrole .= '/'.$sec;
                   5215:                     }
                   5216:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5217:                         $no_ownblock = 1;
                   5218:                         last;
                   5219:                     }
                   5220:                 }
                   5221:             }
                   5222:             # if they have 'evb' priv and are currently not playing student
                   5223:             next if (($no_ownblock) &&
                   5224:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5225:         }
1.474     raeburn  5226:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5227:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5228:             if ($sec ne 'none') {
1.482     raeburn  5229:                 $checkrole .= '/'.$sec;
1.474     raeburn  5230:             }
1.490     raeburn  5231:             if ($otheruser) {
                   5232:                 # Resource belongs to user other than current user.
                   5233:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5234:                 my (%allroles,%userroles);
                   5235:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5236:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5237:                         my ($trole,$tdom,$tnum,$tsec);
                   5238:                         if ($entry =~ /^cr/) {
                   5239:                             ($trole,$tdom,$tnum,$tsec) = 
                   5240:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5241:                         } else {
                   5242:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5243:                         }
                   5244:                         my ($spec,$area,$trest);
                   5245:                         $area = '/'.$tdom.'/'.$tnum;
                   5246:                         $trest = $tnum;
                   5247:                         if ($tsec ne '') {
                   5248:                             $area .= '/'.$tsec;
                   5249:                             $trest .= '/'.$tsec;
                   5250:                         }
                   5251:                         $spec = $trole.'.'.$area;
                   5252:                         if ($trole =~ /^cr/) {
                   5253:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5254:                                                               $tdom,$spec,$trest,$area);
                   5255:                         } else {
                   5256:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5257:                                                                 $tdom,$spec,$trest,$area);
                   5258:                         }
                   5259:                     }
1.1276    raeburn  5260:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5261:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5262:                         if ($1) {
                   5263:                             $no_userblock = 1;
                   5264:                             last;
                   5265:                         }
1.486     raeburn  5266:                     }
                   5267:                 }
1.490     raeburn  5268:             } else {
                   5269:                 # Resource belongs to current user
                   5270:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5271:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5272:                     $no_ownblock = 1;
                   5273:                     last;
                   5274:                 }
1.474     raeburn  5275:             }
                   5276:         }
                   5277:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5278:         next if (($no_ownblock) &&
1.491     albertel 5279:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5280:         next if ($no_userblock);
1.474     raeburn  5281: 
1.1303    raeburn  5282:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5283:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5284: 
1.1062    raeburn  5285:         my ($start,$end,$trigger) = 
                   5286:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5287:         if (($start != 0) && 
                   5288:             (($startblock == 0) || ($startblock > $start))) {
                   5289:             $startblock = $start;
1.1062    raeburn  5290:             if ($trigger ne '') {
                   5291:                 $triggerblock = $trigger;
                   5292:             }
1.502     raeburn  5293:         }
                   5294:         if (($end != 0)  &&
                   5295:             (($endblock == 0) || ($endblock < $end))) {
                   5296:             $endblock = $end;
1.1062    raeburn  5297:             if ($trigger ne '') {
                   5298:                 $triggerblock = $trigger;
                   5299:             }
1.502     raeburn  5300:         }
1.490     raeburn  5301:     }
1.1062    raeburn  5302:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5303: }
                   5304: 
                   5305: sub get_blocks {
1.1062    raeburn  5306:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5307:     my $startblock = 0;
                   5308:     my $endblock = 0;
1.1062    raeburn  5309:     my $triggerblock = '';
1.490     raeburn  5310:     my $course = $cdom.'_'.$cnum;
                   5311:     $setters->{$course} = {};
                   5312:     $setters->{$course}{'staff'} = [];
                   5313:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5314:     $setters->{$course}{'triggers'} = [];
                   5315:     my (@blockers,%triggered);
                   5316:     my $now = time;
                   5317:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5318:     if ($activity eq 'docs') {
                   5319:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5320:         foreach my $block (@blockers) {
                   5321:             if ($block =~ /^firstaccess____(.+)$/) {
                   5322:                 my $item = $1;
                   5323:                 my $type = 'map';
                   5324:                 my $timersymb = $item;
                   5325:                 if ($item eq 'course') {
                   5326:                     $type = 'course';
                   5327:                 } elsif ($item =~ /___\d+___/) {
                   5328:                     $type = 'resource';
                   5329:                 } else {
                   5330:                     $timersymb = &Apache::lonnet::symbread($item);
                   5331:                 }
                   5332:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5333:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5334:                 $triggered{$block} = {
                   5335:                                        start => $start,
                   5336:                                        end   => $end,
                   5337:                                        type  => $type,
                   5338:                                      };
                   5339:             }
                   5340:         }
                   5341:     } else {
                   5342:         foreach my $block (keys(%commblocks)) {
                   5343:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5344:                 my ($start,$end) = ($1,$2);
                   5345:                 if ($start <= time && $end >= time) {
                   5346:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5347:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5348:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5349:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5350:                                     push(@blockers,$block);
                   5351:                                 }
                   5352:                             }
                   5353:                         }
                   5354:                     }
                   5355:                 }
                   5356:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5357:                 my $item = $1;
                   5358:                 my $timersymb = $item; 
                   5359:                 my $type = 'map';
                   5360:                 if ($item eq 'course') {
                   5361:                     $type = 'course';
                   5362:                 } elsif ($item =~ /___\d+___/) {
                   5363:                     $type = 'resource';
                   5364:                 } else {
                   5365:                     $timersymb = &Apache::lonnet::symbread($item);
                   5366:                 }
                   5367:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5368:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5369:                 if ($start && $end) {
                   5370:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5371:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5372:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5373:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5374:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5375:                                         push(@blockers,$block);
                   5376:                                         $triggered{$block} = {
                   5377:                                                                start => $start,
                   5378:                                                                end   => $end,
                   5379:                                                                type  => $type,
                   5380:                                                              };
                   5381:                                     }
                   5382:                                 }
                   5383:                             }
1.1062    raeburn  5384:                         }
                   5385:                     }
1.490     raeburn  5386:                 }
1.1062    raeburn  5387:             }
                   5388:         }
                   5389:     }
                   5390:     foreach my $blocker (@blockers) {
                   5391:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5392:             &parse_block_record($commblocks{$blocker});
                   5393:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5394:         my ($start,$end,$triggertype);
                   5395:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5396:             ($start,$end) = ($1,$2);
                   5397:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5398:             $start = $triggered{$blocker}{'start'};
                   5399:             $end = $triggered{$blocker}{'end'};
                   5400:             $triggertype = $triggered{$blocker}{'type'};
                   5401:         }
                   5402:         if ($start) {
                   5403:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5404:             if ($triggertype) {
                   5405:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5406:             } else {
                   5407:                 push(@{$$setters{$course}{'triggers'}},0);
                   5408:             }
                   5409:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5410:                 $startblock = $start;
                   5411:                 if ($triggertype) {
                   5412:                     $triggerblock = $blocker;
1.474     raeburn  5413:                 }
                   5414:             }
1.1062    raeburn  5415:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5416:                $endblock = $end;
                   5417:                if ($triggertype) {
                   5418:                    $triggerblock = $blocker;
                   5419:                }
                   5420:             }
1.474     raeburn  5421:         }
                   5422:     }
1.1062    raeburn  5423:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5424: }
                   5425: 
                   5426: sub parse_block_record {
                   5427:     my ($record) = @_;
                   5428:     my ($setuname,$setudom,$title,$blocks);
                   5429:     if (ref($record) eq 'HASH') {
                   5430:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5431:         $title = &unescape($record->{'event'});
                   5432:         $blocks = $record->{'blocks'};
                   5433:     } else {
                   5434:         my @data = split(/:/,$record,3);
                   5435:         if (scalar(@data) eq 2) {
                   5436:             $title = $data[1];
                   5437:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5438:         } else {
                   5439:             ($setuname,$setudom,$title) = @data;
                   5440:         }
                   5441:         $blocks = { 'com' => 'on' };
                   5442:     }
                   5443:     return ($setuname,$setudom,$title,$blocks);
                   5444: }
                   5445: 
1.854     kalberla 5446: sub blocking_status {
1.1189    raeburn  5447:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5448:     my %setters;
1.890     droeschl 5449: 
1.1061    raeburn  5450: # check for active blocking
1.1062    raeburn  5451:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5452:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5453:     my $blocked = 0;
                   5454:     if ($startblock && $endblock) {
                   5455:         $blocked = 1;
                   5456:     }
1.890     droeschl 5457: 
1.1061    raeburn  5458: # caller just wants to know whether a block is active
                   5459:     if (!wantarray) { return $blocked; }
                   5460: 
                   5461: # build a link to a popup window containing the details
                   5462:     my $querystring  = "?activity=$activity";
                   5463: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5464:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5465:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5466:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5467:     } elsif ($activity eq 'docs') {
                   5468:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5469:     }
1.1061    raeburn  5470: 
                   5471:     my $output .= <<'END_MYBLOCK';
                   5472: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5473:     var options = "width=" + w + ",height=" + h + ",";
                   5474:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5475:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5476:     var newWin = window.open(url, wdwName, options);
                   5477:     newWin.focus();
                   5478: }
1.890     droeschl 5479: END_MYBLOCK
1.854     kalberla 5480: 
1.1061    raeburn  5481:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5482:   
1.1061    raeburn  5483:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5484:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5485:     my $class = 'LC_comblock';
1.1062    raeburn  5486:     if ($activity eq 'docs') {
                   5487:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5488:         $class = '';
1.1063    raeburn  5489:     } elsif ($activity eq 'printout') {
                   5490:         $text = &mt('Printing Blocked');
1.1232    raeburn  5491:     } elsif ($activity eq 'passwd') {
                   5492:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5493:     } elsif ($activity eq 'grades') {
                   5494:         $text = &mt('Gradebook Blocked');
1.1346  ! raeburn  5495:     } elsif ($activity eq 'search') {
        !          5496:         $text = &mt('Search Blocked');
1.1282    raeburn  5497:     } elsif ($activity eq 'alert') {
                   5498:         $text = &mt('Checking Critical Messages Blocked');
                   5499:     } elsif ($activity eq 'reinit') {
                   5500:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5501:     }
1.1061    raeburn  5502:     $output .= <<"END_BLOCK";
1.1217    raeburn  5503: <div class='$class'>
1.869     kalberla 5504:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5505:   title='$text'>
                   5506:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5507:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5508:   title='$text'>$text</a>
1.867     kalberla 5509: </div>
                   5510: 
                   5511: END_BLOCK
1.474     raeburn  5512: 
1.1061    raeburn  5513:     return ($blocked, $output);
1.854     kalberla 5514: }
1.490     raeburn  5515: 
1.60      matthew  5516: ###############################################
                   5517: 
1.682     raeburn  5518: sub check_ip_acc {
1.1201    raeburn  5519:     my ($acc,$clientip)=@_;
1.682     raeburn  5520:     &Apache::lonxml::debug("acc is $acc");
                   5521:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5522:         return 1;
                   5523:     }
1.1339    raeburn  5524:     my ($ip,$allowed);
                   5525:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5526:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5527:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5528:     } else {
                   5529:         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
                   5530:     }
1.682     raeburn  5531: 
                   5532:     my $name;
1.1219    raeburn  5533:     my %access = (
                   5534:                      allowfrom => 1,
                   5535:                      denyfrom  => 0,
                   5536:                  );
                   5537:     my @allows;
                   5538:     my @denies;
                   5539:     foreach my $item (split(',',$acc)) {
                   5540:         $item =~ s/^\s*//;
                   5541:         $item =~ s/\s*$//;
                   5542:         my $pattern;
                   5543:         if ($item =~ /^\!(.+)$/) {
                   5544:             push(@denies,$1);
                   5545:         } else {
                   5546:             push(@allows,$item);
                   5547:         }
                   5548:    }
                   5549:    my $numdenies = scalar(@denies);
                   5550:    my $numallows = scalar(@allows);
                   5551:    my $count = 0;
                   5552:    foreach my $pattern (@denies,@allows) {
                   5553:         $count ++; 
                   5554:         my $acctype = 'allowfrom';
                   5555:         if ($count <= $numdenies) {
                   5556:             $acctype = 'denyfrom';
                   5557:         }
1.682     raeburn  5558:         if ($pattern =~ /\*$/) {
                   5559:             #35.8.*
                   5560:             $pattern=~s/\*//;
1.1219    raeburn  5561:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5562:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5563:             #35.8.3.[34-56]
                   5564:             my $low=$2;
                   5565:             my $high=$3;
                   5566:             $pattern=$1;
                   5567:             if ($ip =~ /^\Q$pattern\E/) {
                   5568:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5569:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5570:             }
                   5571:         } elsif ($pattern =~ /^\*/) {
                   5572:             #*.msu.edu
                   5573:             $pattern=~s/\*//;
                   5574:             if (!defined($name)) {
                   5575:                 use Socket;
                   5576:                 my $netaddr=inet_aton($ip);
                   5577:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5578:             }
1.1219    raeburn  5579:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5580:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5581:             #127.0.0.1
1.1219    raeburn  5582:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5583:         } else {
                   5584:             #some.name.com
                   5585:             if (!defined($name)) {
                   5586:                 use Socket;
                   5587:                 my $netaddr=inet_aton($ip);
                   5588:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5589:             }
1.1219    raeburn  5590:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5591:         }
                   5592:         if ($allowed =~ /^(0|1)$/) { last; }
                   5593:     }
                   5594:     if ($allowed eq '') {
                   5595:         if ($numdenies && !$numallows) {
                   5596:             $allowed = 1;
                   5597:         } else {
                   5598:             $allowed = 0;
1.682     raeburn  5599:         }
                   5600:     }
                   5601:     return $allowed;
                   5602: }
                   5603: 
                   5604: ###############################################
                   5605: 
1.60      matthew  5606: =pod
                   5607: 
1.112     bowersj2 5608: =head1 Domain Template Functions
                   5609: 
                   5610: =over 4
                   5611: 
                   5612: =item * &determinedomain()
1.60      matthew  5613: 
                   5614: Inputs: $domain (usually will be undef)
                   5615: 
1.63      www      5616: Returns: Determines which domain should be used for designs
1.60      matthew  5617: 
                   5618: =cut
1.54      www      5619: 
1.60      matthew  5620: ###############################################
1.63      www      5621: sub determinedomain {
                   5622:     my $domain=shift;
1.531     albertel 5623:     if (! $domain) {
1.60      matthew  5624:         # Determine domain if we have not been given one
1.893     raeburn  5625:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5626:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5627:         if ($env{'request.role.domain'}) { 
                   5628:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5629:         }
                   5630:     }
1.63      www      5631:     return $domain;
                   5632: }
                   5633: ###############################################
1.517     raeburn  5634: 
1.518     albertel 5635: sub devalidate_domconfig_cache {
                   5636:     my ($udom)=@_;
                   5637:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5638: }
                   5639: 
                   5640: # ---------------------- Get domain configuration for a domain
                   5641: sub get_domainconf {
                   5642:     my ($udom) = @_;
                   5643:     my $cachetime=1800;
                   5644:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5645:     if (defined($cached)) { return %{$result}; }
                   5646: 
                   5647:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5648: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5649:     my (%designhash,%legacy);
1.518     albertel 5650:     if (keys(%domconfig) > 0) {
                   5651:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5652:             if (keys(%{$domconfig{'login'}})) {
                   5653:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5654:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5655:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5656:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5657:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5658:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5659:                                         if ($key eq 'loginvia') {
                   5660:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5661:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5662:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5663:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5664: 
                   5665:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5666:                                                 } else {
                   5667:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5668:                                                 }
1.948     raeburn  5669:                                             }
1.1208    raeburn  5670:                                         } elsif ($key eq 'headtag') {
                   5671:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5672:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5673:                                             }
1.946     raeburn  5674:                                         }
1.1208    raeburn  5675:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5676:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5677:                                         }
1.946     raeburn  5678:                                     }
                   5679:                                 }
                   5680:                             }
                   5681:                         } else {
                   5682:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5683:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5684:                                     $domconfig{'login'}{$key}{$img};
                   5685:                             }
1.699     raeburn  5686:                         }
                   5687:                     } else {
                   5688:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5689:                     }
1.632     raeburn  5690:                 }
                   5691:             } else {
                   5692:                 $legacy{'login'} = 1;
1.518     albertel 5693:             }
1.632     raeburn  5694:         } else {
                   5695:             $legacy{'login'} = 1;
1.518     albertel 5696:         }
                   5697:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5698:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5699:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5700:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5701:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5702:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5703:                         }
1.518     albertel 5704:                     }
                   5705:                 }
1.632     raeburn  5706:             } else {
                   5707:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5708:             }
1.632     raeburn  5709:         } else {
                   5710:             $legacy{'rolecolors'} = 1;
1.518     albertel 5711:         }
1.948     raeburn  5712:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5713:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5714:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5715:             }
                   5716:         }
1.632     raeburn  5717:         if (keys(%legacy) > 0) {
                   5718:             my %legacyhash = &get_legacy_domconf($udom);
                   5719:             foreach my $item (keys(%legacyhash)) {
                   5720:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5721:                     if ($legacy{'login'}) { 
                   5722:                         $designhash{$item} = $legacyhash{$item};
                   5723:                     }
                   5724:                 } else {
                   5725:                     if ($legacy{'rolecolors'}) {
                   5726:                         $designhash{$item} = $legacyhash{$item};
                   5727:                     }
1.518     albertel 5728:                 }
                   5729:             }
                   5730:         }
1.632     raeburn  5731:     } else {
                   5732:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5733:     }
                   5734:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5735: 				  $cachetime);
                   5736:     return %designhash;
                   5737: }
                   5738: 
1.632     raeburn  5739: sub get_legacy_domconf {
                   5740:     my ($udom) = @_;
                   5741:     my %legacyhash;
                   5742:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5743:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5744:     if (-e $designfile) {
1.1317    raeburn  5745:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5746:             while (my $line = <$fh>) {
                   5747:                 next if ($line =~ /^\#/);
                   5748:                 chomp($line);
                   5749:                 my ($key,$val)=(split(/\=/,$line));
                   5750:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5751:             }
                   5752:             close($fh);
                   5753:         }
                   5754:     }
1.1026    raeburn  5755:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5756:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5757:     }
                   5758:     return %legacyhash;
                   5759: }
                   5760: 
1.63      www      5761: =pod
                   5762: 
1.112     bowersj2 5763: =item * &domainlogo()
1.63      www      5764: 
                   5765: Inputs: $domain (usually will be undef)
                   5766: 
                   5767: Returns: A link to a domain logo, if the domain logo exists.
                   5768: If the domain logo does not exist, a description of the domain.
                   5769: 
                   5770: =cut
1.112     bowersj2 5771: 
1.63      www      5772: ###############################################
                   5773: sub domainlogo {
1.517     raeburn  5774:     my $domain = &determinedomain(shift);
1.518     albertel 5775:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5776:     # See if there is a logo
                   5777:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5778:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5779:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5780: 	    if ($imgsrc =~ m{^/res/}) {
                   5781: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5782: 		&Apache::lonnet::repcopy($local_name);
                   5783: 	    }
                   5784: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5785:         } 
                   5786:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5787:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5788:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5789:     } else {
1.60      matthew  5790:         return '';
1.59      www      5791:     }
                   5792: }
1.63      www      5793: ##############################################
                   5794: 
                   5795: =pod
                   5796: 
1.112     bowersj2 5797: =item * &designparm()
1.63      www      5798: 
                   5799: Inputs: $which parameter; $domain (usually will be undef)
                   5800: 
                   5801: Returns: value of designparamter $which
                   5802: 
                   5803: =cut
1.112     bowersj2 5804: 
1.397     albertel 5805: 
1.400     albertel 5806: ##############################################
1.397     albertel 5807: sub designparm {
                   5808:     my ($which,$domain)=@_;
                   5809:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5810:         return $env{'environment.color.'.$which};
1.96      www      5811:     }
1.63      www      5812:     $domain=&determinedomain($domain);
1.1016    raeburn  5813:     my %domdesign;
                   5814:     unless ($domain eq 'public') {
                   5815:         %domdesign = &get_domainconf($domain);
                   5816:     }
1.520     raeburn  5817:     my $output;
1.517     raeburn  5818:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5819:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5820:     } else {
1.520     raeburn  5821:         $output = $defaultdesign{$which};
                   5822:     }
                   5823:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5824:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5825:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5826:             if ($output =~ m{^/res/}) {
                   5827:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5828:                 &Apache::lonnet::repcopy($local_name);
                   5829:             }
1.520     raeburn  5830:             $output = &lonhttpdurl($output);
                   5831:         }
1.63      www      5832:     }
1.520     raeburn  5833:     return $output;
1.63      www      5834: }
1.59      www      5835: 
1.822     bisitz   5836: ##############################################
                   5837: =pod
                   5838: 
1.832     bisitz   5839: =item * &authorspace()
                   5840: 
1.1028    raeburn  5841: Inputs: $url (usually will be undef).
1.832     bisitz   5842: 
1.1132    raeburn  5843: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5844:          directory being viewed (or for which action is being taken). 
                   5845:          If $url is provided, and begins /priv/<domain>/<uname>
                   5846:          the path will be that portion of the $context argument.
                   5847:          Otherwise the path will be for the author space of the current
                   5848:          user when the current role is author, or for that of the 
                   5849:          co-author/assistant co-author space when the current role 
                   5850:          is co-author or assistant co-author.
1.832     bisitz   5851: 
                   5852: =cut
                   5853: 
                   5854: sub authorspace {
1.1028    raeburn  5855:     my ($url) = @_;
                   5856:     if ($url ne '') {
                   5857:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5858:            return $1;
                   5859:         }
                   5860:     }
1.832     bisitz   5861:     my $caname = '';
1.1024    www      5862:     my $cadom = '';
1.1028    raeburn  5863:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5864:         ($cadom,$caname) =
1.832     bisitz   5865:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5866:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5867:         $caname = $env{'user.name'};
1.1024    www      5868:         $cadom = $env{'user.domain'};
1.832     bisitz   5869:     }
1.1028    raeburn  5870:     if (($caname ne '') && ($cadom ne '')) {
                   5871:         return "/priv/$cadom/$caname/";
                   5872:     }
                   5873:     return;
1.832     bisitz   5874: }
                   5875: 
                   5876: ##############################################
                   5877: =pod
                   5878: 
1.822     bisitz   5879: =item * &head_subbox()
                   5880: 
                   5881: Inputs: $content (contains HTML code with page functions, etc.)
                   5882: 
                   5883: Returns: HTML div with $content
                   5884:          To be included in page header
                   5885: 
                   5886: =cut
                   5887: 
                   5888: sub head_subbox {
                   5889:     my ($content)=@_;
                   5890:     my $output =
1.993     raeburn  5891:         '<div class="LC_head_subbox">'
1.822     bisitz   5892:        .$content
                   5893:        .'</div>'
                   5894: }
                   5895: 
                   5896: ##############################################
                   5897: =pod
                   5898: 
                   5899: =item * &CSTR_pageheader()
                   5900: 
1.1026    raeburn  5901: Input: (optional) filename from which breadcrumb trail is built.
                   5902:        In most cases no input as needed, as $env{'request.filename'}
                   5903:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5904: 
                   5905: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5906:          To be included on Authoring Space pages
1.822     bisitz   5907: 
                   5908: =cut
                   5909: 
                   5910: sub CSTR_pageheader {
1.1026    raeburn  5911:     my ($trailfile) = @_;
                   5912:     if ($trailfile eq '') {
                   5913:         $trailfile = $env{'request.filename'};
                   5914:     }
                   5915: 
                   5916: # this is for resources; directories have customtitle, and crumbs
                   5917: # and select recent are created in lonpubdir.pm
                   5918: 
                   5919:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5920:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5921:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5922:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5923:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5924: 
                   5925:     my $parentpath = '';
                   5926:     my $lastitem = '';
                   5927:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5928:         $parentpath = $1;
                   5929:         $lastitem = $2;
                   5930:     } else {
                   5931:         $lastitem = $thisdisfn;
                   5932:     }
1.921     bisitz   5933: 
1.1246    raeburn  5934:     my ($crsauthor,$title);
                   5935:     if (($env{'request.course.id'}) &&
                   5936:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5937:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5938:         $crsauthor = 1;
                   5939:         $title = &mt('Course Authoring Space');
                   5940:     } else {
                   5941:         $title = &mt('Authoring Space');
                   5942:     }
                   5943: 
1.1314    raeburn  5944:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  5945:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  5946:         $target = '';
                   5947:         $crumbtarget = '';
1.1313    raeburn  5948:     }
                   5949: 
1.921     bisitz   5950:     my $output =
1.822     bisitz   5951:          '<div>'
                   5952:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5953:         .'<b>'.$title.'</b> '
1.1314    raeburn  5954:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5955:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5956: 
                   5957:     if ($lastitem) {
                   5958:         $output .=
                   5959:              '<span class="LC_filename">'
                   5960:             .$lastitem
                   5961:             .'</span>';
                   5962:     }
1.1245    raeburn  5963: 
1.1246    raeburn  5964:     if ($crsauthor) {
                   5965:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5966:     } else {
                   5967:         $output .=
                   5968:              '<br />'
1.1314    raeburn  5969:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  5970:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5971:             .'</form>'
                   5972:             .&Apache::lonmenu::constspaceform();
                   5973:     }
                   5974:     $output .= '</div>';
1.921     bisitz   5975: 
                   5976:     return $output;
1.822     bisitz   5977: }
                   5978: 
1.60      matthew  5979: ###############################################
                   5980: ###############################################
                   5981: 
                   5982: =pod
                   5983: 
1.112     bowersj2 5984: =back
                   5985: 
1.549     albertel 5986: =head1 HTML Helpers
1.112     bowersj2 5987: 
                   5988: =over 4
                   5989: 
                   5990: =item * &bodytag()
1.60      matthew  5991: 
                   5992: Returns a uniform header for LON-CAPA web pages.
                   5993: 
                   5994: Inputs: 
                   5995: 
1.112     bowersj2 5996: =over 4
                   5997: 
                   5998: =item * $title, A title to be displayed on the page.
                   5999: 
                   6000: =item * $function, the current role (can be undef).
                   6001: 
                   6002: =item * $addentries, extra parameters for the <body> tag.
                   6003: 
                   6004: =item * $bodyonly, if defined, only return the <body> tag.
                   6005: 
                   6006: =item * $domain, if defined, force a given domain.
                   6007: 
                   6008: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6009:             text interface only)
1.60      matthew  6010: 
1.814     bisitz   6011: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6012:                      navigational links
1.317     albertel 6013: 
1.338     albertel 6014: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6015: 
1.460     albertel 6016: =item * $args, optional argument valid values are
                   6017:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6018:             use_absolute     -> for external resource or syllabus, this will
                   6019:                                 contain https://<hostname> if server uses
                   6020:                                 https (as per hosts.tab), but request is for http
                   6021:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6022: 
1.1096    raeburn  6023: =item * $advtoolsref, optional argument, ref to an array containing
                   6024:             inlineremote items to be added in "Functions" menu below
                   6025:             breadcrumbs.
                   6026: 
1.1316    raeburn  6027: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6028:             course, if LON-CAPA is in LTI Provider context. Value is
                   6029:             the scope of use, i.e., launch was for access to a single, a map
                   6030:             or the entire course.
                   6031: 
                   6032: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6033:             context, this will contain the URL for the landing item in
                   6034:             the course, after launch from an LTI Consumer
                   6035: 
1.1318    raeburn  6036: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6037:             context, this will contain a reference to hash of items
                   6038:             to be included in the page header and/or inline menu.
                   6039: 
1.112     bowersj2 6040: =back
                   6041: 
1.60      matthew  6042: Returns: A uniform header for LON-CAPA web pages.  
                   6043: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6044: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6045: other decorations will be returned.
                   6046: 
                   6047: =cut
                   6048: 
1.54      www      6049: sub bodytag {
1.831     bisitz   6050:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1318    raeburn  6051:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,$ltimenu)=@_;
1.339     albertel 6052: 
1.954     raeburn  6053:     my $public;
                   6054:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6055:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6056:         $public = 1;
                   6057:     }
1.460     albertel 6058:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6059:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6060:     my $hostname = $args->{'hostname'};
1.339     albertel 6061: 
1.183     matthew  6062:     $function = &get_users_function() if (!$function);
1.339     albertel 6063:     my $img =    &designparm($function.'.img',$domain);
                   6064:     my $font =   &designparm($function.'.font',$domain);
                   6065:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6066: 
1.803     bisitz   6067:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6068: 		   'bgcolor' => $pgbg,
1.339     albertel 6069: 		   'text'    => $font,
                   6070:                    'alink'   => &designparm($function.'.alink',$domain),
                   6071: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6072: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6073:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6074: 
1.63      www      6075:  # role and realm
1.1178    raeburn  6076:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6077:     if ($realm) {
                   6078:         $realm = '/'.$realm;
                   6079:     }
1.378     raeburn  6080:     if ($role  eq 'ca') {
1.479     albertel 6081:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6082:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6083:     } 
1.55      www      6084: # realm
1.258     albertel 6085:     if ($env{'request.course.id'}) {
1.378     raeburn  6086:         if ($env{'request.role'} !~ /^cr/) {
                   6087:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6088:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6089:             if ($env{'request.role.desc'}) {
                   6090:                 $role = $env{'request.role.desc'};
                   6091:             } else {
                   6092:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6093:             }
1.1257    raeburn  6094:         } else {
                   6095:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6096:         }
1.898     raeburn  6097:         if ($env{'request.course.sec'}) {
                   6098:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   6099:         }   
1.359     albertel 6100: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  6101:     } else {
                   6102:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6103:     }
1.433     albertel 6104: 
1.359     albertel 6105:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6106: 
1.438     albertel 6107:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6108: 
1.101     www      6109: # construct main body tag
1.359     albertel 6110:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6111: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6112: 
1.1131    raeburn  6113:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6114: 
1.1130    raeburn  6115:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6116:         return $bodytag;
1.1130    raeburn  6117:     }
1.359     albertel 6118: 
1.954     raeburn  6119:     if ($public) {
1.433     albertel 6120: 	undef($role);
                   6121:     }
1.1318    raeburn  6122: 
                   6123:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   6124:         if (ref($ltimenu) eq 'HASH') {
                   6125:             unless ($ltimenu->{'role'}) {
                   6126:                 undef($role);
                   6127:             }
                   6128:             unless ($ltimenu->{'coursetitle'}) {
                   6129:                 $realm='&nbsp;';
                   6130:             }
                   6131:         }
                   6132:     }
                   6133: 
1.762     bisitz   6134:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6135:     #
                   6136:     # Extra info if you are the DC
                   6137:     my $dc_info = '';
                   6138:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   6139:                         $env{'course.'.$env{'request.course.id'}.
                   6140:                                  '.domain'}.'/'})) {
                   6141:         my $cid = $env{'request.course.id'};
1.917     raeburn  6142:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6143:         $dc_info =~ s/\s+$//;
1.359     albertel 6144:     }
                   6145: 
1.1237    raeburn  6146:     my $crstype;
                   6147:     if ($env{'request.course.id'}) {
                   6148:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   6149:     } elsif ($args->{'crstype'}) {
                   6150:         $crstype = $args->{'crstype'};
                   6151:     }
                   6152:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6153:         undef($role);
                   6154:     } else {
1.1242    raeburn  6155:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6156:     }
1.853     droeschl 6157: 
1.903     droeschl 6158:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6159: 
                   6160:         #    if ($env{'request.state'} eq 'construct') {
                   6161:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6162:         #    }
                   6163: 
1.1130    raeburn  6164:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6165:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6166: 
1.1318    raeburn  6167:         unless ($args->{'no_primary_menu'}) {
                   6168:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu);
1.359     albertel 6169: 
1.1318    raeburn  6170:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6171:                 if ($dc_info) {
                   6172:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6173:                 }
                   6174:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6175:                                <em>$realm</em> $dc_info</div>|;
                   6176:                 return $bodytag;
                   6177:             }
1.894     droeschl 6178: 
1.1318    raeburn  6179:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6180:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6181:             }
1.916     droeschl 6182: 
1.1318    raeburn  6183:             $bodytag .= $right;
1.852     droeschl 6184: 
1.1318    raeburn  6185:             if ($dc_info) {
                   6186:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6187:             }
                   6188:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6189:         }
1.916     droeschl 6190: 
1.1169    raeburn  6191:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6192:         if ($args->{'no_secondary_menu'}) {
                   6193:             return $bodytag;
                   6194:         }
1.1169    raeburn  6195:         #don't show menus for public users
1.954     raeburn  6196:         if (!$public){
1.1318    raeburn  6197:             unless ($args->{'no_inline_menu'}) {
                   6198:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6199:                                                             $args->{'no_primary_menu'});
                   6200:             }
1.903     droeschl 6201:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6202:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6203:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6204:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6205:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6206:             } elsif ($forcereg) {
                   6207:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6208:                                                             $args->{'group'},
1.1274    raeburn  6209:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6210:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6211:             } else {
                   6212:                 $bodytag .= 
                   6213:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6214:                                                         $forcereg,$args->{'group'},
                   6215:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6216:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6217:             }
1.903     droeschl 6218:         }else{
                   6219:             # this is to seperate menu from content when there's no secondary
                   6220:             # menu. Especially needed for public accessible ressources.
                   6221:             $bodytag .= '<hr style="clear:both" />';
                   6222:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6223:         }
1.903     droeschl 6224: 
1.235     raeburn  6225:         return $bodytag;
1.182     matthew  6226: }
                   6227: 
1.917     raeburn  6228: sub dc_courseid_toggle {
                   6229:     my ($dc_info) = @_;
1.980     raeburn  6230:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6231:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6232:            &mt('(More ...)').'</a></span>'.
                   6233:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6234: }
                   6235: 
1.330     albertel 6236: sub make_attr_string {
                   6237:     my ($register,$attr_ref) = @_;
                   6238: 
                   6239:     if ($attr_ref && !ref($attr_ref)) {
                   6240: 	die("addentries Must be a hash ref ".
                   6241: 	    join(':',caller(1))." ".
                   6242: 	    join(':',caller(0))." ");
                   6243:     }
                   6244: 
                   6245:     if ($register) {
1.339     albertel 6246: 	my ($on_load,$on_unload);
                   6247: 	foreach my $key (keys(%{$attr_ref})) {
                   6248: 	    if      (lc($key) eq 'onload') {
                   6249: 		$on_load.=$attr_ref->{$key}.';';
                   6250: 		delete($attr_ref->{$key});
                   6251: 
                   6252: 	    } elsif (lc($key) eq 'onunload') {
                   6253: 		$on_unload.=$attr_ref->{$key}.';';
                   6254: 		delete($attr_ref->{$key});
                   6255: 	    }
                   6256: 	}
1.953     droeschl 6257: 	$attr_ref->{'onload'}  = $on_load;
                   6258: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6259:     }
1.339     albertel 6260: 
1.330     albertel 6261:     my $attr_string;
1.1159    raeburn  6262:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6263: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6264:     }
                   6265:     return $attr_string;
                   6266: }
                   6267: 
                   6268: 
1.182     matthew  6269: ###############################################
1.251     albertel 6270: ###############################################
                   6271: 
                   6272: =pod
                   6273: 
                   6274: =item * &endbodytag()
                   6275: 
                   6276: Returns a uniform footer for LON-CAPA web pages.
                   6277: 
1.635     raeburn  6278: Inputs: 1 - optional reference to an args hash
                   6279: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6280: a 'Continue' link is not displayed if the page contains an
                   6281: internal redirect in the <head></head> section,
                   6282: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6283: 
                   6284: =cut
                   6285: 
                   6286: sub endbodytag {
1.635     raeburn  6287:     my ($args) = @_;
1.1080    raeburn  6288:     my $endbodytag;
                   6289:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6290:         $endbodytag='</body>';
                   6291:     }
1.315     albertel 6292:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6293:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6294: 	    $endbodytag=
                   6295: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6296: 	        &mt('Continue').'</a>'.
                   6297: 	        $endbodytag;
                   6298:         }
1.315     albertel 6299:     }
1.251     albertel 6300:     return $endbodytag;
                   6301: }
                   6302: 
1.352     albertel 6303: =pod
                   6304: 
                   6305: =item * &standard_css()
                   6306: 
                   6307: Returns a style sheet
                   6308: 
                   6309: Inputs: (all optional)
                   6310:             domain         -> force to color decorate a page for a specific
                   6311:                                domain
                   6312:             function       -> force usage of a specific rolish color scheme
                   6313:             bgcolor        -> override the default page bgcolor
                   6314: 
                   6315: =cut
                   6316: 
1.343     albertel 6317: sub standard_css {
1.345     albertel 6318:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6319:     $function  = &get_users_function() if (!$function);
                   6320:     my $img    = &designparm($function.'.img',   $domain);
                   6321:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6322:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6323:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6324: #second colour for later usage
1.345     albertel 6325:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6326:     my $pgbg_or_bgcolor =
                   6327: 	         $bgcolor ||
1.352     albertel 6328: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6329:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6330:     my $alink  = &designparm($function.'.alink', $domain);
                   6331:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6332:     my $link   = &designparm($function.'.link',  $domain);
                   6333: 
1.602     albertel 6334:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6335:     my $mono                 = 'monospace';
1.850     bisitz   6336:     my $data_table_head      = $sidebg;
                   6337:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6338:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6339:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6340:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6341:     my $mail_new             = '#FFBB77';
                   6342:     my $mail_new_hover       = '#DD9955';
                   6343:     my $mail_read            = '#BBBB77';
                   6344:     my $mail_read_hover      = '#999944';
                   6345:     my $mail_replied         = '#AAAA88';
                   6346:     my $mail_replied_hover   = '#888855';
                   6347:     my $mail_other           = '#99BBBB';
                   6348:     my $mail_other_hover     = '#669999';
1.391     albertel 6349:     my $table_header         = '#DDDDDD';
1.489     raeburn  6350:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6351:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6352:     my $button_hover         = '#BF2317';
1.392     albertel 6353: 
1.608     albertel 6354:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6355:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6356:                                              : '0 3px 0 4px';
1.448     albertel 6357: 
1.523     albertel 6358: 
1.343     albertel 6359:     return <<END;
1.947     droeschl 6360: 
                   6361: /* needed for iframe to allow 100% height in FF */
                   6362: body, html { 
                   6363:     margin: 0;
                   6364:     padding: 0 0.5%;
                   6365:     height: 99%; /* to avoid scrollbars */
                   6366: }
                   6367: 
1.795     www      6368: body {
1.911     bisitz   6369:   font-family: $sans;
                   6370:   line-height:130%;
                   6371:   font-size:0.83em;
                   6372:   color:$font;
1.795     www      6373: }
                   6374: 
1.959     onken    6375: a:focus,
                   6376: a:focus img {
1.795     www      6377:   color: red;
                   6378: }
1.698     harmsja  6379: 
1.911     bisitz   6380: form, .inline {
                   6381:   display: inline;
1.795     www      6382: }
1.721     harmsja  6383: 
1.795     www      6384: .LC_right {
1.911     bisitz   6385:   text-align:right;
1.795     www      6386: }
                   6387: 
                   6388: .LC_middle {
1.911     bisitz   6389:   vertical-align:middle;
1.795     www      6390: }
1.721     harmsja  6391: 
1.1130    raeburn  6392: .LC_floatleft {
                   6393:   float: left;
                   6394: }
                   6395: 
                   6396: .LC_floatright {
                   6397:   float: right;
                   6398: }
                   6399: 
1.911     bisitz   6400: .LC_400Box {
                   6401:   width:400px;
                   6402: }
1.721     harmsja  6403: 
1.947     droeschl 6404: .LC_iframecontainer {
                   6405:     width: 98%;
                   6406:     margin: 0;
                   6407:     position: fixed;
                   6408:     top: 8.5em;
                   6409:     bottom: 0;
                   6410: }
                   6411: 
                   6412: .LC_iframecontainer iframe{
                   6413:     border: none;
                   6414:     width: 100%;
                   6415:     height: 100%;
                   6416: }
                   6417: 
1.778     bisitz   6418: .LC_filename {
                   6419:   font-family: $mono;
                   6420:   white-space:pre;
1.921     bisitz   6421:   font-size: 120%;
1.778     bisitz   6422: }
                   6423: 
                   6424: .LC_fileicon {
                   6425:   border: none;
                   6426:   height: 1.3em;
                   6427:   vertical-align: text-bottom;
                   6428:   margin-right: 0.3em;
                   6429:   text-decoration:none;
                   6430: }
                   6431: 
1.1008    www      6432: .LC_setting {
                   6433:   text-decoration:underline;
                   6434: }
                   6435: 
1.350     albertel 6436: .LC_error {
                   6437:   color: red;
                   6438: }
1.795     www      6439: 
1.1097    bisitz   6440: .LC_warning {
                   6441:   color: darkorange;
                   6442: }
                   6443: 
1.457     albertel 6444: .LC_diff_removed {
1.733     bisitz   6445:   color: red;
1.394     albertel 6446: }
1.532     albertel 6447: 
                   6448: .LC_info,
1.457     albertel 6449: .LC_success,
                   6450: .LC_diff_added {
1.350     albertel 6451:   color: green;
                   6452: }
1.795     www      6453: 
1.802     bisitz   6454: div.LC_confirm_box {
                   6455:   background-color: #FAFAFA;
                   6456:   border: 1px solid $lg_border_color;
                   6457:   margin-right: 0;
                   6458:   padding: 5px;
                   6459: }
                   6460: 
                   6461: div.LC_confirm_box .LC_error img,
                   6462: div.LC_confirm_box .LC_success img {
                   6463:   vertical-align: middle;
                   6464: }
                   6465: 
1.1242    raeburn  6466: .LC_maxwidth {
                   6467:   max-width: 100%;
                   6468:   height: auto;
                   6469: }
                   6470: 
1.1243    raeburn  6471: .LC_textsize_mobile {
                   6472:   \@media only screen and (max-device-width: 480px) {
                   6473:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6474:   }
                   6475: }
                   6476: 
1.440     albertel 6477: .LC_icon {
1.771     droeschl 6478:   border: none;
1.790     droeschl 6479:   vertical-align: middle;
1.771     droeschl 6480: }
                   6481: 
1.543     albertel 6482: .LC_docs_spacer {
                   6483:   width: 25px;
                   6484:   height: 1px;
1.771     droeschl 6485:   border: none;
1.543     albertel 6486: }
1.346     albertel 6487: 
1.532     albertel 6488: .LC_internal_info {
1.735     bisitz   6489:   color: #999999;
1.532     albertel 6490: }
                   6491: 
1.794     www      6492: .LC_discussion {
1.1050    www      6493:   background: $data_table_dark;
1.911     bisitz   6494:   border: 1px solid black;
                   6495:   margin: 2px;
1.794     www      6496: }
                   6497: 
                   6498: .LC_disc_action_left {
1.1050    www      6499:   background: $sidebg;
1.911     bisitz   6500:   text-align: left;
1.1050    www      6501:   padding: 4px;
                   6502:   margin: 2px;
1.794     www      6503: }
                   6504: 
                   6505: .LC_disc_action_right {
1.1050    www      6506:   background: $sidebg;
1.911     bisitz   6507:   text-align: right;
1.1050    www      6508:   padding: 4px;
                   6509:   margin: 2px;
1.794     www      6510: }
                   6511: 
                   6512: .LC_disc_new_item {
1.911     bisitz   6513:   background: white;
                   6514:   border: 2px solid red;
1.1050    www      6515:   margin: 4px;
                   6516:   padding: 4px;
1.794     www      6517: }
                   6518: 
                   6519: .LC_disc_old_item {
1.911     bisitz   6520:   background: white;
1.1050    www      6521:   margin: 4px;
                   6522:   padding: 4px;
1.794     www      6523: }
                   6524: 
1.458     albertel 6525: table.LC_pastsubmission {
                   6526:   border: 1px solid black;
                   6527:   margin: 2px;
                   6528: }
                   6529: 
1.924     bisitz   6530: table#LC_menubuttons {
1.345     albertel 6531:   width: 100%;
                   6532:   background: $pgbg;
1.392     albertel 6533:   border: 2px;
1.402     albertel 6534:   border-collapse: separate;
1.803     bisitz   6535:   padding: 0;
1.345     albertel 6536: }
1.392     albertel 6537: 
1.801     tempelho 6538: table#LC_title_bar a {
                   6539:   color: $fontmenu;
                   6540: }
1.836     bisitz   6541: 
1.807     droeschl 6542: table#LC_title_bar {
1.819     tempelho 6543:   clear: both;
1.836     bisitz   6544:   display: none;
1.807     droeschl 6545: }
                   6546: 
1.795     www      6547: table#LC_title_bar,
1.933     droeschl 6548: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6549: table#LC_title_bar.LC_with_remote {
1.359     albertel 6550:   width: 100%;
1.392     albertel 6551:   border-color: $pgbg;
                   6552:   border-style: solid;
                   6553:   border-width: $border;
1.379     albertel 6554:   background: $pgbg;
1.801     tempelho 6555:   color: $fontmenu;
1.392     albertel 6556:   border-collapse: collapse;
1.803     bisitz   6557:   padding: 0;
1.819     tempelho 6558:   margin: 0;
1.359     albertel 6559: }
1.795     www      6560: 
1.933     droeschl 6561: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6562:     margin: 0;
                   6563:     padding: 0;
1.933     droeschl 6564:     position: relative;
                   6565:     list-style: none;
1.913     droeschl 6566: }
1.933     droeschl 6567: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6568:     display: inline;
                   6569: }
1.933     droeschl 6570: 
                   6571: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6572:     padding: 0;
1.933     droeschl 6573:     margin: 0;
                   6574:     float: left;
1.913     droeschl 6575: }
1.933     droeschl 6576: .LC_breadcrumb_tools_tools {
                   6577:     padding: 0;
                   6578:     margin: 0;
1.913     droeschl 6579:     float: right;
                   6580: }
                   6581: 
1.1240    raeburn  6582: .LC_placement_prog {
                   6583:     padding-right: 20px;
                   6584:     font-weight: bold;
                   6585:     font-size: 90%;
                   6586: }
                   6587: 
1.359     albertel 6588: table#LC_title_bar td {
                   6589:   background: $tabbg;
                   6590: }
1.795     www      6591: 
1.911     bisitz   6592: table#LC_menubuttons img {
1.803     bisitz   6593:   border: none;
1.346     albertel 6594: }
1.795     www      6595: 
1.842     droeschl 6596: .LC_breadcrumbs_component {
1.911     bisitz   6597:   float: right;
                   6598:   margin: 0 1em;
1.357     albertel 6599: }
1.842     droeschl 6600: .LC_breadcrumbs_component img {
1.911     bisitz   6601:   vertical-align: middle;
1.777     tempelho 6602: }
1.795     www      6603: 
1.1243    raeburn  6604: .LC_breadcrumbs_hoverable {
                   6605:   background: $sidebg;
                   6606: }
                   6607: 
1.383     albertel 6608: td.LC_table_cell_checkbox {
                   6609:   text-align: center;
                   6610: }
1.795     www      6611: 
                   6612: .LC_fontsize_small {
1.911     bisitz   6613:   font-size: 70%;
1.705     tempelho 6614: }
                   6615: 
1.844     bisitz   6616: #LC_breadcrumbs {
1.911     bisitz   6617:   clear:both;
                   6618:   background: $sidebg;
                   6619:   border-bottom: 1px solid $lg_border_color;
                   6620:   line-height: 2.5em;
1.933     droeschl 6621:   overflow: hidden;
1.911     bisitz   6622:   margin: 0;
                   6623:   padding: 0;
1.995     raeburn  6624:   text-align: left;
1.819     tempelho 6625: }
1.862     bisitz   6626: 
1.1098    bisitz   6627: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6628:   clear:both;
                   6629:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6630:   border: 1px solid $sidebg;
1.1098    bisitz   6631:   margin: 0 0 10px 0;
1.966     bisitz   6632:   padding: 3px;
1.995     raeburn  6633:   text-align: left;
1.822     bisitz   6634: }
                   6635: 
1.795     www      6636: .LC_fontsize_medium {
1.911     bisitz   6637:   font-size: 85%;
1.705     tempelho 6638: }
                   6639: 
1.795     www      6640: .LC_fontsize_large {
1.911     bisitz   6641:   font-size: 120%;
1.705     tempelho 6642: }
                   6643: 
1.346     albertel 6644: .LC_menubuttons_inline_text {
                   6645:   color: $font;
1.698     harmsja  6646:   font-size: 90%;
1.701     harmsja  6647:   padding-left:3px;
1.346     albertel 6648: }
                   6649: 
1.934     droeschl 6650: .LC_menubuttons_inline_text img{
                   6651:   vertical-align: middle;
                   6652: }
                   6653: 
1.1051    www      6654: li.LC_menubuttons_inline_text img {
1.951     onken    6655:   cursor:pointer;
1.1002    droeschl 6656:   text-decoration: none;
1.951     onken    6657: }
                   6658: 
1.526     www      6659: .LC_menubuttons_link {
                   6660:   text-decoration: none;
                   6661: }
1.795     www      6662: 
1.522     albertel 6663: .LC_menubuttons_category {
1.521     www      6664:   color: $font;
1.526     www      6665:   background: $pgbg;
1.521     www      6666:   font-size: larger;
                   6667:   font-weight: bold;
                   6668: }
                   6669: 
1.346     albertel 6670: td.LC_menubuttons_text {
1.911     bisitz   6671:   color: $font;
1.346     albertel 6672: }
1.706     harmsja  6673: 
1.346     albertel 6674: .LC_current_location {
                   6675:   background: $tabbg;
                   6676: }
1.795     www      6677: 
1.1286    raeburn  6678: td.LC_zero_height {
                   6679:   line-height: 0; 
                   6680:   cellpadding: 0;
                   6681: }
                   6682: 
1.938     bisitz   6683: table.LC_data_table {
1.347     albertel 6684:   border: 1px solid #000000;
1.402     albertel 6685:   border-collapse: separate;
1.426     albertel 6686:   border-spacing: 1px;
1.610     albertel 6687:   background: $pgbg;
1.347     albertel 6688: }
1.795     www      6689: 
1.422     albertel 6690: .LC_data_table_dense {
                   6691:   font-size: small;
                   6692: }
1.795     www      6693: 
1.507     raeburn  6694: table.LC_nested_outer {
                   6695:   border: 1px solid #000000;
1.589     raeburn  6696:   border-collapse: collapse;
1.803     bisitz   6697:   border-spacing: 0;
1.507     raeburn  6698:   width: 100%;
                   6699: }
1.795     www      6700: 
1.879     raeburn  6701: table.LC_innerpickbox,
1.507     raeburn  6702: table.LC_nested {
1.803     bisitz   6703:   border: none;
1.589     raeburn  6704:   border-collapse: collapse;
1.803     bisitz   6705:   border-spacing: 0;
1.507     raeburn  6706:   width: 100%;
                   6707: }
1.795     www      6708: 
1.911     bisitz   6709: table.LC_data_table tr th,
                   6710: table.LC_calendar tr th,
1.879     raeburn  6711: table.LC_prior_tries tr th,
                   6712: table.LC_innerpickbox tr th {
1.349     albertel 6713:   font-weight: bold;
                   6714:   background-color: $data_table_head;
1.801     tempelho 6715:   color:$fontmenu;
1.701     harmsja  6716:   font-size:90%;
1.347     albertel 6717: }
1.795     www      6718: 
1.879     raeburn  6719: table.LC_innerpickbox tr th,
                   6720: table.LC_innerpickbox tr td {
                   6721:   vertical-align: top;
                   6722: }
                   6723: 
1.711     raeburn  6724: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6725:   background-color: #CCCCCC;
1.711     raeburn  6726:   font-weight: bold;
                   6727:   text-align: left;
                   6728: }
1.795     www      6729: 
1.912     bisitz   6730: table.LC_data_table tr.LC_odd_row > td {
                   6731:   background-color: $data_table_light;
                   6732:   padding: 2px;
                   6733:   vertical-align: top;
                   6734: }
                   6735: 
1.809     bisitz   6736: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6737:   background-color: $data_table_light;
1.912     bisitz   6738:   vertical-align: top;
                   6739: }
                   6740: 
                   6741: table.LC_data_table tr.LC_even_row > td {
                   6742:   background-color: $data_table_dark;
1.425     albertel 6743:   padding: 2px;
1.900     bisitz   6744:   vertical-align: top;
1.347     albertel 6745: }
1.795     www      6746: 
1.809     bisitz   6747: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6748:   background-color: $data_table_dark;
1.900     bisitz   6749:   vertical-align: top;
1.347     albertel 6750: }
1.795     www      6751: 
1.425     albertel 6752: table.LC_data_table tr.LC_data_table_highlight td {
                   6753:   background-color: $data_table_darker;
                   6754: }
1.795     www      6755: 
1.639     raeburn  6756: table.LC_data_table tr td.LC_leftcol_header {
                   6757:   background-color: $data_table_head;
                   6758:   font-weight: bold;
                   6759: }
1.795     www      6760: 
1.451     albertel 6761: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6762: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6763:   font-weight: bold;
                   6764:   font-style: italic;
                   6765:   text-align: center;
                   6766:   padding: 8px;
1.347     albertel 6767: }
1.795     www      6768: 
1.1114    raeburn  6769: table.LC_data_table tr.LC_empty_row td,
                   6770: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6771:   background-color: $sidebg;
                   6772: }
                   6773: 
                   6774: table.LC_nested tr.LC_empty_row td {
                   6775:   background-color: #FFFFFF;
                   6776: }
                   6777: 
1.890     droeschl 6778: table.LC_caption {
                   6779: }
                   6780: 
1.507     raeburn  6781: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6782:   padding: 4ex
                   6783: }
1.795     www      6784: 
1.507     raeburn  6785: table.LC_nested_outer tr th {
                   6786:   font-weight: bold;
1.801     tempelho 6787:   color:$fontmenu;
1.507     raeburn  6788:   background-color: $data_table_head;
1.701     harmsja  6789:   font-size: small;
1.507     raeburn  6790:   border-bottom: 1px solid #000000;
                   6791: }
1.795     www      6792: 
1.507     raeburn  6793: table.LC_nested_outer tr td.LC_subheader {
                   6794:   background-color: $data_table_head;
                   6795:   font-weight: bold;
                   6796:   font-size: small;
                   6797:   border-bottom: 1px solid #000000;
                   6798:   text-align: right;
1.451     albertel 6799: }
1.795     www      6800: 
1.507     raeburn  6801: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6802:   background-color: #CCCCCC;
1.451     albertel 6803:   font-weight: bold;
                   6804:   font-size: small;
1.507     raeburn  6805:   text-align: center;
                   6806: }
1.795     www      6807: 
1.589     raeburn  6808: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6809: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6810:   text-align: left;
1.451     albertel 6811: }
1.795     www      6812: 
1.507     raeburn  6813: table.LC_nested td {
1.735     bisitz   6814:   background-color: #FFFFFF;
1.451     albertel 6815:   font-size: small;
1.507     raeburn  6816: }
1.795     www      6817: 
1.507     raeburn  6818: table.LC_nested_outer tr th.LC_right_item,
                   6819: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6820: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6821: table.LC_nested tr td.LC_right_item {
1.451     albertel 6822:   text-align: right;
                   6823: }
                   6824: 
1.507     raeburn  6825: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6826:   background-color: #EEEEEE;
1.451     albertel 6827: }
                   6828: 
1.473     raeburn  6829: table.LC_createuser {
                   6830: }
                   6831: 
                   6832: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6833:   font-size: small;
1.473     raeburn  6834: }
                   6835: 
                   6836: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6837:   background-color: #CCCCCC;
1.473     raeburn  6838:   font-weight: bold;
                   6839:   text-align: center;
                   6840: }
                   6841: 
1.349     albertel 6842: table.LC_calendar {
                   6843:   border: 1px solid #000000;
                   6844:   border-collapse: collapse;
1.917     raeburn  6845:   width: 98%;
1.349     albertel 6846: }
1.795     www      6847: 
1.349     albertel 6848: table.LC_calendar_pickdate {
                   6849:   font-size: xx-small;
                   6850: }
1.795     www      6851: 
1.349     albertel 6852: table.LC_calendar tr td {
                   6853:   border: 1px solid #000000;
                   6854:   vertical-align: top;
1.917     raeburn  6855:   width: 14%;
1.349     albertel 6856: }
1.795     www      6857: 
1.349     albertel 6858: table.LC_calendar tr td.LC_calendar_day_empty {
                   6859:   background-color: $data_table_dark;
                   6860: }
1.795     www      6861: 
1.779     bisitz   6862: table.LC_calendar tr td.LC_calendar_day_current {
                   6863:   background-color: $data_table_highlight;
1.777     tempelho 6864: }
1.795     www      6865: 
1.938     bisitz   6866: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6867:   background-color: $mail_new;
                   6868: }
1.795     www      6869: 
1.938     bisitz   6870: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6871:   background-color: $mail_new_hover;
                   6872: }
1.795     www      6873: 
1.938     bisitz   6874: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6875:   background-color: $mail_read;
                   6876: }
1.795     www      6877: 
1.938     bisitz   6878: /*
                   6879: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6880:   background-color: $mail_read_hover;
                   6881: }
1.938     bisitz   6882: */
1.795     www      6883: 
1.938     bisitz   6884: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6885:   background-color: $mail_replied;
                   6886: }
1.795     www      6887: 
1.938     bisitz   6888: /*
                   6889: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6890:   background-color: $mail_replied_hover;
                   6891: }
1.938     bisitz   6892: */
1.795     www      6893: 
1.938     bisitz   6894: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6895:   background-color: $mail_other;
                   6896: }
1.795     www      6897: 
1.938     bisitz   6898: /*
                   6899: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6900:   background-color: $mail_other_hover;
                   6901: }
1.938     bisitz   6902: */
1.494     raeburn  6903: 
1.777     tempelho 6904: table.LC_data_table tr > td.LC_browser_file,
                   6905: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6906:   background: #AAEE77;
1.389     albertel 6907: }
1.795     www      6908: 
1.777     tempelho 6909: table.LC_data_table tr > td.LC_browser_file_locked,
                   6910: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6911:   background: #FFAA99;
1.387     albertel 6912: }
1.795     www      6913: 
1.777     tempelho 6914: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6915:   background: #888888;
1.779     bisitz   6916: }
1.795     www      6917: 
1.777     tempelho 6918: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6919: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6920:   background: #F8F866;
1.777     tempelho 6921: }
1.795     www      6922: 
1.696     bisitz   6923: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6924:   background: #E0E8FF;
1.387     albertel 6925: }
1.696     bisitz   6926: 
1.707     bisitz   6927: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6928:   /* background: #77FF77; */
1.707     bisitz   6929: }
1.795     www      6930: 
1.707     bisitz   6931: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6932:   border-right: 8px solid #FFFF77;
1.707     bisitz   6933: }
1.795     www      6934: 
1.707     bisitz   6935: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6936:   border-right: 8px solid #FFAA77;
1.707     bisitz   6937: }
1.795     www      6938: 
1.707     bisitz   6939: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6940:   border-right: 8px solid #FF7777;
1.707     bisitz   6941: }
1.795     www      6942: 
1.707     bisitz   6943: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6944:   border-right: 8px solid #AAFF77;
1.707     bisitz   6945: }
1.795     www      6946: 
1.707     bisitz   6947: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6948:   border-right: 8px solid #11CC55;
1.707     bisitz   6949: }
                   6950: 
1.388     albertel 6951: span.LC_current_location {
1.701     harmsja  6952:   font-size:larger;
1.388     albertel 6953:   background: $pgbg;
                   6954: }
1.387     albertel 6955: 
1.1029    www      6956: span.LC_current_nav_location {
                   6957:   font-weight:bold;
                   6958:   background: $sidebg;
                   6959: }
                   6960: 
1.395     albertel 6961: span.LC_parm_menu_item {
                   6962:   font-size: larger;
                   6963: }
1.795     www      6964: 
1.395     albertel 6965: span.LC_parm_scope_all {
                   6966:   color: red;
                   6967: }
1.795     www      6968: 
1.395     albertel 6969: span.LC_parm_scope_folder {
                   6970:   color: green;
                   6971: }
1.795     www      6972: 
1.395     albertel 6973: span.LC_parm_scope_resource {
                   6974:   color: orange;
                   6975: }
1.795     www      6976: 
1.395     albertel 6977: span.LC_parm_part {
                   6978:   color: blue;
                   6979: }
1.795     www      6980: 
1.911     bisitz   6981: span.LC_parm_folder,
                   6982: span.LC_parm_symb {
1.395     albertel 6983:   font-size: x-small;
                   6984:   font-family: $mono;
                   6985:   color: #AAAAAA;
                   6986: }
                   6987: 
1.977     bisitz   6988: ul.LC_parm_parmlist li {
                   6989:   display: inline-block;
                   6990:   padding: 0.3em 0.8em;
                   6991:   vertical-align: top;
                   6992:   width: 150px;
                   6993:   border-top:1px solid $lg_border_color;
                   6994: }
                   6995: 
1.795     www      6996: td.LC_parm_overview_level_menu,
                   6997: td.LC_parm_overview_map_menu,
                   6998: td.LC_parm_overview_parm_selectors,
                   6999: td.LC_parm_overview_restrictions  {
1.396     albertel 7000:   border: 1px solid black;
                   7001:   border-collapse: collapse;
                   7002: }
1.795     www      7003: 
1.1285    raeburn  7004: span.LC_parm_recursive,
                   7005: td.LC_parm_recursive {
                   7006:   font-weight: bold;
                   7007:   font-size: smaller;
                   7008: }
                   7009: 
1.396     albertel 7010: table.LC_parm_overview_restrictions td {
                   7011:   border-width: 1px 4px 1px 4px;
                   7012:   border-style: solid;
                   7013:   border-color: $pgbg;
                   7014:   text-align: center;
                   7015: }
1.795     www      7016: 
1.396     albertel 7017: table.LC_parm_overview_restrictions th {
                   7018:   background: $tabbg;
                   7019:   border-width: 1px 4px 1px 4px;
                   7020:   border-style: solid;
                   7021:   border-color: $pgbg;
                   7022: }
1.795     www      7023: 
1.398     albertel 7024: table#LC_helpmenu {
1.803     bisitz   7025:   border: none;
1.398     albertel 7026:   height: 55px;
1.803     bisitz   7027:   border-spacing: 0;
1.398     albertel 7028: }
                   7029: 
                   7030: table#LC_helpmenu fieldset legend {
                   7031:   font-size: larger;
                   7032: }
1.795     www      7033: 
1.397     albertel 7034: table#LC_helpmenu_links {
                   7035:   width: 100%;
                   7036:   border: 1px solid black;
                   7037:   background: $pgbg;
1.803     bisitz   7038:   padding: 0;
1.397     albertel 7039:   border-spacing: 1px;
                   7040: }
1.795     www      7041: 
1.397     albertel 7042: table#LC_helpmenu_links tr td {
                   7043:   padding: 1px;
                   7044:   background: $tabbg;
1.399     albertel 7045:   text-align: center;
                   7046:   font-weight: bold;
1.397     albertel 7047: }
1.396     albertel 7048: 
1.795     www      7049: table#LC_helpmenu_links a:link,
                   7050: table#LC_helpmenu_links a:visited,
1.397     albertel 7051: table#LC_helpmenu_links a:active {
                   7052:   text-decoration: none;
                   7053:   color: $font;
                   7054: }
1.795     www      7055: 
1.397     albertel 7056: table#LC_helpmenu_links a:hover {
                   7057:   text-decoration: underline;
                   7058:   color: $vlink;
                   7059: }
1.396     albertel 7060: 
1.417     albertel 7061: .LC_chrt_popup_exists {
                   7062:   border: 1px solid #339933;
                   7063:   margin: -1px;
                   7064: }
1.795     www      7065: 
1.417     albertel 7066: .LC_chrt_popup_up {
                   7067:   border: 1px solid yellow;
                   7068:   margin: -1px;
                   7069: }
1.795     www      7070: 
1.417     albertel 7071: .LC_chrt_popup {
                   7072:   border: 1px solid #8888FF;
                   7073:   background: #CCCCFF;
                   7074: }
1.795     www      7075: 
1.421     albertel 7076: table.LC_pick_box {
                   7077:   border-collapse: separate;
                   7078:   background: white;
                   7079:   border: 1px solid black;
                   7080:   border-spacing: 1px;
                   7081: }
1.795     www      7082: 
1.421     albertel 7083: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7084:   background: $sidebg;
1.421     albertel 7085:   font-weight: bold;
1.900     bisitz   7086:   text-align: left;
1.740     bisitz   7087:   vertical-align: top;
1.421     albertel 7088:   width: 184px;
                   7089:   padding: 8px;
                   7090: }
1.795     www      7091: 
1.579     raeburn  7092: table.LC_pick_box td.LC_pick_box_value {
                   7093:   text-align: left;
                   7094:   padding: 8px;
                   7095: }
1.795     www      7096: 
1.579     raeburn  7097: table.LC_pick_box td.LC_pick_box_select {
                   7098:   text-align: left;
                   7099:   padding: 8px;
                   7100: }
1.795     www      7101: 
1.424     albertel 7102: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7103:   padding: 0;
1.421     albertel 7104:   height: 1px;
                   7105:   background: black;
                   7106: }
1.795     www      7107: 
1.421     albertel 7108: table.LC_pick_box td.LC_pick_box_submit {
                   7109:   text-align: right;
                   7110: }
1.795     www      7111: 
1.579     raeburn  7112: table.LC_pick_box td.LC_evenrow_value {
                   7113:   text-align: left;
                   7114:   padding: 8px;
                   7115:   background-color: $data_table_light;
                   7116: }
1.795     www      7117: 
1.579     raeburn  7118: table.LC_pick_box td.LC_oddrow_value {
                   7119:   text-align: left;
                   7120:   padding: 8px;
                   7121:   background-color: $data_table_light;
                   7122: }
1.795     www      7123: 
1.579     raeburn  7124: span.LC_helpform_receipt_cat {
                   7125:   font-weight: bold;
                   7126: }
1.795     www      7127: 
1.424     albertel 7128: table.LC_group_priv_box {
                   7129:   background: white;
                   7130:   border: 1px solid black;
                   7131:   border-spacing: 1px;
                   7132: }
1.795     www      7133: 
1.424     albertel 7134: table.LC_group_priv_box td.LC_pick_box_title {
                   7135:   background: $tabbg;
                   7136:   font-weight: bold;
                   7137:   text-align: right;
                   7138:   width: 184px;
                   7139: }
1.795     www      7140: 
1.424     albertel 7141: table.LC_group_priv_box td.LC_groups_fixed {
                   7142:   background: $data_table_light;
                   7143:   text-align: center;
                   7144: }
1.795     www      7145: 
1.424     albertel 7146: table.LC_group_priv_box td.LC_groups_optional {
                   7147:   background: $data_table_dark;
                   7148:   text-align: center;
                   7149: }
1.795     www      7150: 
1.424     albertel 7151: table.LC_group_priv_box td.LC_groups_functionality {
                   7152:   background: $data_table_darker;
                   7153:   text-align: center;
                   7154:   font-weight: bold;
                   7155: }
1.795     www      7156: 
1.424     albertel 7157: table.LC_group_priv td {
                   7158:   text-align: left;
1.803     bisitz   7159:   padding: 0;
1.424     albertel 7160: }
                   7161: 
                   7162: .LC_navbuttons {
                   7163:   margin: 2ex 0ex 2ex 0ex;
                   7164: }
1.795     www      7165: 
1.423     albertel 7166: .LC_topic_bar {
                   7167:   font-weight: bold;
                   7168:   background: $tabbg;
1.918     wenzelju 7169:   margin: 1em 0em 1em 2em;
1.805     bisitz   7170:   padding: 3px;
1.918     wenzelju 7171:   font-size: 1.2em;
1.423     albertel 7172: }
1.795     www      7173: 
1.423     albertel 7174: .LC_topic_bar span {
1.918     wenzelju 7175:   left: 0.5em;
                   7176:   position: absolute;
1.423     albertel 7177:   vertical-align: middle;
1.918     wenzelju 7178:   font-size: 1.2em;
1.423     albertel 7179: }
1.795     www      7180: 
1.423     albertel 7181: table.LC_course_group_status {
                   7182:   margin: 20px;
                   7183: }
1.795     www      7184: 
1.423     albertel 7185: table.LC_status_selector td {
                   7186:   vertical-align: top;
                   7187:   text-align: center;
1.424     albertel 7188:   padding: 4px;
                   7189: }
1.795     www      7190: 
1.599     albertel 7191: div.LC_feedback_link {
1.616     albertel 7192:   clear: both;
1.829     kalberla 7193:   background: $sidebg;
1.779     bisitz   7194:   width: 100%;
1.829     kalberla 7195:   padding-bottom: 10px;
                   7196:   border: 1px $tabbg solid;
1.833     kalberla 7197:   height: 22px;
                   7198:   line-height: 22px;
                   7199:   padding-top: 5px;
                   7200: }
                   7201: 
                   7202: div.LC_feedback_link img {
                   7203:   height: 22px;
1.867     kalberla 7204:   vertical-align:middle;
1.829     kalberla 7205: }
                   7206: 
1.911     bisitz   7207: div.LC_feedback_link a {
1.829     kalberla 7208:   text-decoration: none;
1.489     raeburn  7209: }
1.795     www      7210: 
1.867     kalberla 7211: div.LC_comblock {
1.911     bisitz   7212:   display:inline;
1.867     kalberla 7213:   color:$font;
                   7214:   font-size:90%;
                   7215: }
                   7216: 
                   7217: div.LC_feedback_link div.LC_comblock {
                   7218:   padding-left:5px;
                   7219: }
                   7220: 
                   7221: div.LC_feedback_link div.LC_comblock a {
                   7222:   color:$font;
                   7223: }
                   7224: 
1.489     raeburn  7225: span.LC_feedback_link {
1.858     bisitz   7226:   /* background: $feedback_link_bg; */
1.599     albertel 7227:   font-size: larger;
                   7228: }
1.795     www      7229: 
1.599     albertel 7230: span.LC_message_link {
1.858     bisitz   7231:   /* background: $feedback_link_bg; */
1.599     albertel 7232:   font-size: larger;
                   7233:   position: absolute;
                   7234:   right: 1em;
1.489     raeburn  7235: }
1.421     albertel 7236: 
1.515     albertel 7237: table.LC_prior_tries {
1.524     albertel 7238:   border: 1px solid #000000;
                   7239:   border-collapse: separate;
                   7240:   border-spacing: 1px;
1.515     albertel 7241: }
1.523     albertel 7242: 
1.515     albertel 7243: table.LC_prior_tries td {
1.524     albertel 7244:   padding: 2px;
1.515     albertel 7245: }
1.523     albertel 7246: 
                   7247: .LC_answer_correct {
1.795     www      7248:   background: lightgreen;
                   7249:   color: darkgreen;
                   7250:   padding: 6px;
1.523     albertel 7251: }
1.795     www      7252: 
1.523     albertel 7253: .LC_answer_charged_try {
1.797     www      7254:   background: #FFAAAA;
1.795     www      7255:   color: darkred;
                   7256:   padding: 6px;
1.523     albertel 7257: }
1.795     www      7258: 
1.779     bisitz   7259: .LC_answer_not_charged_try,
1.523     albertel 7260: .LC_answer_no_grade,
                   7261: .LC_answer_late {
1.795     www      7262:   background: lightyellow;
1.523     albertel 7263:   color: black;
1.795     www      7264:   padding: 6px;
1.523     albertel 7265: }
1.795     www      7266: 
1.523     albertel 7267: .LC_answer_previous {
1.795     www      7268:   background: lightblue;
                   7269:   color: darkblue;
                   7270:   padding: 6px;
1.523     albertel 7271: }
1.795     www      7272: 
1.779     bisitz   7273: .LC_answer_no_message {
1.777     tempelho 7274:   background: #FFFFFF;
                   7275:   color: black;
1.795     www      7276:   padding: 6px;
1.779     bisitz   7277: }
1.795     www      7278: 
1.1334    raeburn  7279: .LC_answer_unknown,
                   7280: .LC_answer_warning {
1.779     bisitz   7281:   background: orange;
                   7282:   color: black;
1.795     www      7283:   padding: 6px;
1.777     tempelho 7284: }
1.795     www      7285: 
1.529     albertel 7286: span.LC_prior_numerical,
                   7287: span.LC_prior_string,
                   7288: span.LC_prior_custom,
                   7289: span.LC_prior_reaction,
                   7290: span.LC_prior_math {
1.925     bisitz   7291:   font-family: $mono;
1.523     albertel 7292:   white-space: pre;
                   7293: }
                   7294: 
1.525     albertel 7295: span.LC_prior_string {
1.925     bisitz   7296:   font-family: $mono;
1.525     albertel 7297:   white-space: pre;
                   7298: }
                   7299: 
1.523     albertel 7300: table.LC_prior_option {
                   7301:   width: 100%;
                   7302:   border-collapse: collapse;
                   7303: }
1.795     www      7304: 
1.911     bisitz   7305: table.LC_prior_rank,
1.795     www      7306: table.LC_prior_match {
1.528     albertel 7307:   border-collapse: collapse;
                   7308: }
1.795     www      7309: 
1.528     albertel 7310: table.LC_prior_option tr td,
                   7311: table.LC_prior_rank tr td,
                   7312: table.LC_prior_match tr td {
1.524     albertel 7313:   border: 1px solid #000000;
1.515     albertel 7314: }
                   7315: 
1.855     bisitz   7316: .LC_nobreak {
1.544     albertel 7317:   white-space: nowrap;
1.519     raeburn  7318: }
                   7319: 
1.576     raeburn  7320: span.LC_cusr_emph {
                   7321:   font-style: italic;
                   7322: }
                   7323: 
1.633     raeburn  7324: span.LC_cusr_subheading {
                   7325:   font-weight: normal;
                   7326:   font-size: 85%;
                   7327: }
                   7328: 
1.861     bisitz   7329: div.LC_docs_entry_move {
1.859     bisitz   7330:   border: 1px solid #BBBBBB;
1.545     albertel 7331:   background: #DDDDDD;
1.861     bisitz   7332:   width: 22px;
1.859     bisitz   7333:   padding: 1px;
                   7334:   margin: 0;
1.545     albertel 7335: }
                   7336: 
1.861     bisitz   7337: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7338: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7339:   font-size: x-small;
                   7340: }
1.795     www      7341: 
1.861     bisitz   7342: .LC_docs_entry_parameter {
                   7343:   white-space: nowrap;
                   7344: }
                   7345: 
1.544     albertel 7346: .LC_docs_copy {
1.545     albertel 7347:   color: #000099;
1.544     albertel 7348: }
1.795     www      7349: 
1.544     albertel 7350: .LC_docs_cut {
1.545     albertel 7351:   color: #550044;
1.544     albertel 7352: }
1.795     www      7353: 
1.544     albertel 7354: .LC_docs_rename {
1.545     albertel 7355:   color: #009900;
1.544     albertel 7356: }
1.795     www      7357: 
1.544     albertel 7358: .LC_docs_remove {
1.545     albertel 7359:   color: #990000;
                   7360: }
                   7361: 
1.1284    raeburn  7362: .LC_docs_alias {
                   7363:   color: #440055;  
                   7364: }
                   7365: 
1.1286    raeburn  7366: .LC_domprefs_email,
1.1284    raeburn  7367: .LC_docs_alias_name,
1.547     albertel 7368: .LC_docs_reinit_warn,
                   7369: .LC_docs_ext_edit {
                   7370:   font-size: x-small;
                   7371: }
                   7372: 
1.545     albertel 7373: table.LC_docs_adddocs td,
                   7374: table.LC_docs_adddocs th {
                   7375:   border: 1px solid #BBBBBB;
                   7376:   padding: 4px;
                   7377:   background: #DDDDDD;
1.543     albertel 7378: }
                   7379: 
1.584     albertel 7380: table.LC_sty_begin {
                   7381:   background: #BBFFBB;
                   7382: }
1.795     www      7383: 
1.584     albertel 7384: table.LC_sty_end {
                   7385:   background: #FFBBBB;
                   7386: }
                   7387: 
1.589     raeburn  7388: table.LC_double_column {
1.803     bisitz   7389:   border-width: 0;
1.589     raeburn  7390:   border-collapse: collapse;
                   7391:   width: 100%;
                   7392:   padding: 2px;
                   7393: }
                   7394: 
                   7395: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7396:   top: 2px;
1.589     raeburn  7397:   left: 2px;
                   7398:   width: 47%;
                   7399:   vertical-align: top;
                   7400: }
                   7401: 
                   7402: table.LC_double_column tr td.LC_right_col {
                   7403:   top: 2px;
1.779     bisitz   7404:   right: 2px;
1.589     raeburn  7405:   width: 47%;
                   7406:   vertical-align: top;
                   7407: }
                   7408: 
1.591     raeburn  7409: div.LC_left_float {
                   7410:   float: left;
                   7411:   padding-right: 5%;
1.597     albertel 7412:   padding-bottom: 4px;
1.591     raeburn  7413: }
                   7414: 
                   7415: div.LC_clear_float_header {
1.597     albertel 7416:   padding-bottom: 2px;
1.591     raeburn  7417: }
                   7418: 
                   7419: div.LC_clear_float_footer {
1.597     albertel 7420:   padding-top: 10px;
1.591     raeburn  7421:   clear: both;
                   7422: }
                   7423: 
1.597     albertel 7424: div.LC_grade_show_user {
1.941     bisitz   7425: /*  border-left: 5px solid $sidebg; */
                   7426:   border-top: 5px solid #000000;
                   7427:   margin: 50px 0 0 0;
1.936     bisitz   7428:   padding: 15px 0 5px 10px;
1.597     albertel 7429: }
1.795     www      7430: 
1.936     bisitz   7431: div.LC_grade_show_user_odd_row {
1.941     bisitz   7432: /*  border-left: 5px solid #000000; */
                   7433: }
                   7434: 
                   7435: div.LC_grade_show_user div.LC_Box {
                   7436:   margin-right: 50px;
1.597     albertel 7437: }
                   7438: 
                   7439: div.LC_grade_submissions,
                   7440: div.LC_grade_message_center,
1.936     bisitz   7441: div.LC_grade_info_links {
1.597     albertel 7442:   margin: 5px;
                   7443:   width: 99%;
                   7444:   background: #FFFFFF;
                   7445: }
1.795     www      7446: 
1.597     albertel 7447: div.LC_grade_submissions_header,
1.936     bisitz   7448: div.LC_grade_message_center_header {
1.705     tempelho 7449:   font-weight: bold;
                   7450:   font-size: large;
1.597     albertel 7451: }
1.795     www      7452: 
1.597     albertel 7453: div.LC_grade_submissions_body,
1.936     bisitz   7454: div.LC_grade_message_center_body {
1.597     albertel 7455:   border: 1px solid black;
                   7456:   width: 99%;
                   7457:   background: #FFFFFF;
                   7458: }
1.795     www      7459: 
1.613     albertel 7460: table.LC_scantron_action {
                   7461:   width: 100%;
                   7462: }
1.795     www      7463: 
1.613     albertel 7464: table.LC_scantron_action tr th {
1.698     harmsja  7465:   font-weight:bold;
                   7466:   font-style:normal;
1.613     albertel 7467: }
1.795     www      7468: 
1.779     bisitz   7469: .LC_edit_problem_header,
1.614     albertel 7470: div.LC_edit_problem_footer {
1.705     tempelho 7471:   font-weight: normal;
                   7472:   font-size:  medium;
1.602     albertel 7473:   margin: 2px;
1.1060    bisitz   7474:   background-color: $sidebg;
1.600     albertel 7475: }
1.795     www      7476: 
1.600     albertel 7477: div.LC_edit_problem_header,
1.602     albertel 7478: div.LC_edit_problem_header div,
1.614     albertel 7479: div.LC_edit_problem_footer,
                   7480: div.LC_edit_problem_footer div,
1.602     albertel 7481: div.LC_edit_problem_editxml_header,
                   7482: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7483:   z-index: 100;
1.600     albertel 7484: }
1.795     www      7485: 
1.600     albertel 7486: div.LC_edit_problem_header_title {
1.705     tempelho 7487:   font-weight: bold;
                   7488:   font-size: larger;
1.602     albertel 7489:   background: $tabbg;
                   7490:   padding: 3px;
1.1060    bisitz   7491:   margin: 0 0 5px 0;
1.602     albertel 7492: }
1.795     www      7493: 
1.602     albertel 7494: table.LC_edit_problem_header_title {
                   7495:   width: 100%;
1.600     albertel 7496:   background: $tabbg;
1.602     albertel 7497: }
                   7498: 
1.1205    golterma 7499: div.LC_edit_actionbar {
                   7500:     background-color: $sidebg;
1.1218    droeschl 7501:     margin: 0;
                   7502:     padding: 0;
                   7503:     line-height: 200%;
1.602     albertel 7504: }
1.795     www      7505: 
1.1218    droeschl 7506: div.LC_edit_actionbar div{
                   7507:     padding: 0;
                   7508:     margin: 0;
                   7509:     display: inline-block;
1.600     albertel 7510: }
1.795     www      7511: 
1.1124    bisitz   7512: .LC_edit_opt {
                   7513:   padding-left: 1em;
                   7514:   white-space: nowrap;
                   7515: }
                   7516: 
1.1152    golterma 7517: .LC_edit_problem_latexhelper{
                   7518:     text-align: right;
                   7519: }
                   7520: 
                   7521: #LC_edit_problem_colorful div{
                   7522:     margin-left: 40px;
                   7523: }
                   7524: 
1.1205    golterma 7525: #LC_edit_problem_codemirror div{
                   7526:     margin-left: 0px;
                   7527: }
                   7528: 
1.911     bisitz   7529: img.stift {
1.803     bisitz   7530:   border-width: 0;
                   7531:   vertical-align: middle;
1.677     riegler  7532: }
1.680     riegler  7533: 
1.923     bisitz   7534: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7535:   vertical-align: top;
1.777     tempelho 7536: }
1.795     www      7537: 
1.716     raeburn  7538: div.LC_createcourse {
1.911     bisitz   7539:   margin: 10px 10px 10px 10px;
1.716     raeburn  7540: }
                   7541: 
1.917     raeburn  7542: .LC_dccid {
1.1130    raeburn  7543:   float: right;
1.917     raeburn  7544:   margin: 0.2em 0 0 0;
                   7545:   padding: 0;
                   7546:   font-size: 90%;
                   7547:   display:none;
                   7548: }
                   7549: 
1.897     wenzelju 7550: ol.LC_primary_menu a:hover,
1.721     harmsja  7551: ol#LC_MenuBreadcrumbs a:hover,
                   7552: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7553: ul#LC_secondary_menu a:hover,
1.721     harmsja  7554: .LC_FormSectionClearButton input:hover
1.795     www      7555: ul.LC_TabContent   li:hover a {
1.952     onken    7556:   color:$button_hover;
1.911     bisitz   7557:   text-decoration:none;
1.693     droeschl 7558: }
                   7559: 
1.779     bisitz   7560: h1 {
1.911     bisitz   7561:   padding: 0;
                   7562:   line-height:130%;
1.693     droeschl 7563: }
1.698     harmsja  7564: 
1.911     bisitz   7565: h2,
                   7566: h3,
                   7567: h4,
                   7568: h5,
                   7569: h6 {
                   7570:   margin: 5px 0 5px 0;
                   7571:   padding: 0;
                   7572:   line-height:130%;
1.693     droeschl 7573: }
1.795     www      7574: 
                   7575: .LC_hcell {
1.911     bisitz   7576:   padding:3px 15px 3px 15px;
                   7577:   margin: 0;
                   7578:   background-color:$tabbg;
                   7579:   color:$fontmenu;
                   7580:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7581: }
1.795     www      7582: 
1.840     bisitz   7583: .LC_Box > .LC_hcell {
1.911     bisitz   7584:   margin: 0 -10px 10px -10px;
1.835     bisitz   7585: }
                   7586: 
1.721     harmsja  7587: .LC_noBorder {
1.911     bisitz   7588:   border: 0;
1.698     harmsja  7589: }
1.693     droeschl 7590: 
1.721     harmsja  7591: .LC_FormSectionClearButton input {
1.911     bisitz   7592:   background-color:transparent;
                   7593:   border: none;
                   7594:   cursor:pointer;
                   7595:   text-decoration:underline;
1.693     droeschl 7596: }
1.763     bisitz   7597: 
                   7598: .LC_help_open_topic {
1.911     bisitz   7599:   color: #FFFFFF;
                   7600:   background-color: #EEEEFF;
                   7601:   margin: 1px;
                   7602:   padding: 4px;
                   7603:   border: 1px solid #000033;
                   7604:   white-space: nowrap;
                   7605:   /* vertical-align: middle; */
1.759     neumanie 7606: }
1.693     droeschl 7607: 
1.911     bisitz   7608: dl,
                   7609: ul,
                   7610: div,
                   7611: fieldset {
                   7612:   margin: 10px 10px 10px 0;
                   7613:   /* overflow: hidden; */
1.693     droeschl 7614: }
1.795     www      7615: 
1.1211    raeburn  7616: article.geogebraweb div {
                   7617:     margin: 0;
                   7618: }
                   7619: 
1.838     bisitz   7620: fieldset > legend {
1.911     bisitz   7621:   font-weight: bold;
                   7622:   padding: 0 5px 0 5px;
1.838     bisitz   7623: }
                   7624: 
1.813     bisitz   7625: #LC_nav_bar {
1.911     bisitz   7626:   float: left;
1.995     raeburn  7627:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7628:   margin: 0 0 2px 0;
1.807     droeschl 7629: }
                   7630: 
1.916     droeschl 7631: #LC_realm {
                   7632:   margin: 0.2em 0 0 0;
                   7633:   padding: 0;
                   7634:   font-weight: bold;
                   7635:   text-align: center;
1.995     raeburn  7636:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7637: }
                   7638: 
1.911     bisitz   7639: #LC_nav_bar em {
                   7640:   font-weight: bold;
                   7641:   font-style: normal;
1.807     droeschl 7642: }
                   7643: 
1.897     wenzelju 7644: ol.LC_primary_menu {
1.934     droeschl 7645:   margin: 0;
1.1076    raeburn  7646:   padding: 0;
1.807     droeschl 7647: }
                   7648: 
1.852     droeschl 7649: ol#LC_PathBreadcrumbs {
1.911     bisitz   7650:   margin: 0;
1.693     droeschl 7651: }
                   7652: 
1.897     wenzelju 7653: ol.LC_primary_menu li {
1.1076    raeburn  7654:   color: RGB(80, 80, 80);
                   7655:   vertical-align: middle;
                   7656:   text-align: left;
                   7657:   list-style: none;
1.1205    golterma 7658:   position: relative;
1.1076    raeburn  7659:   float: left;
1.1205    golterma 7660:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7661:   line-height: 1.5em;
1.1076    raeburn  7662: }
                   7663: 
1.1205    golterma 7664: ol.LC_primary_menu li a,
                   7665: ol.LC_primary_menu li p {
1.1076    raeburn  7666:   display: block;
                   7667:   margin: 0;
                   7668:   padding: 0 5px 0 10px;
                   7669:   text-decoration: none;
                   7670: }
                   7671: 
1.1205    golterma 7672: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7673:   display: inline-block;
                   7674:   width: 95%;
                   7675:   text-align: left;
                   7676: }
                   7677: 
                   7678: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7679:   display: inline-block;	
                   7680:   width: 5%;
                   7681:   float: right;
                   7682:   text-align: right;
                   7683:   font-size: 70%;
                   7684: }
                   7685: 
                   7686: ol.LC_primary_menu ul {
1.1076    raeburn  7687:   display: none;
1.1205    golterma 7688:   width: 15em;
1.1076    raeburn  7689:   background-color: $data_table_light;
1.1205    golterma 7690:   position: absolute;
                   7691:   top: 100%;
1.1076    raeburn  7692: }
                   7693: 
1.1205    golterma 7694: ol.LC_primary_menu ul ul {
                   7695:   left: 100%;
                   7696:   top: 0;
                   7697: }
                   7698: 
                   7699: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7700:   display: block;
                   7701:   position: absolute;
                   7702:   margin: 0;
                   7703:   padding: 0;
1.1078    raeburn  7704:   z-index: 2;
1.1076    raeburn  7705: }
                   7706: 
                   7707: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7708: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7709:   font-size: 90%;
1.911     bisitz   7710:   vertical-align: top;
1.1076    raeburn  7711:   float: none;
1.1079    raeburn  7712:   border-left: 1px solid black;
                   7713:   border-right: 1px solid black;
1.1205    golterma 7714: /* A dark bottom border to visualize different menu options; 
                   7715: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7716:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7717: }
                   7718: 
1.1205    golterma 7719: ol.LC_primary_menu li li p:hover {
                   7720:   color:$button_hover;
                   7721:   text-decoration:none;
                   7722:   background-color:$data_table_dark;
1.1076    raeburn  7723: }
                   7724: 
                   7725: ol.LC_primary_menu li li a:hover {
                   7726:    color:$button_hover;
                   7727:    background-color:$data_table_dark;
1.693     droeschl 7728: }
                   7729: 
1.1205    golterma 7730: /* Font-size equal to the size of the predecessors*/
                   7731: ol.LC_primary_menu li:hover li li {
                   7732:   font-size: 100%;
                   7733: }
                   7734: 
1.897     wenzelju 7735: ol.LC_primary_menu li img {
1.911     bisitz   7736:   vertical-align: bottom;
1.934     droeschl 7737:   height: 1.1em;
1.1077    raeburn  7738:   margin: 0.2em 0 0 0;
1.693     droeschl 7739: }
                   7740: 
1.897     wenzelju 7741: ol.LC_primary_menu a {
1.911     bisitz   7742:   color: RGB(80, 80, 80);
                   7743:   text-decoration: none;
1.693     droeschl 7744: }
1.795     www      7745: 
1.949     droeschl 7746: ol.LC_primary_menu a.LC_new_message {
                   7747:   font-weight:bold;
                   7748:   color: darkred;
                   7749: }
                   7750: 
1.975     raeburn  7751: ol.LC_docs_parameters {
                   7752:   margin-left: 0;
                   7753:   padding: 0;
                   7754:   list-style: none;
                   7755: }
                   7756: 
                   7757: ol.LC_docs_parameters li {
                   7758:   margin: 0;
                   7759:   padding-right: 20px;
                   7760:   display: inline;
                   7761: }
                   7762: 
1.976     raeburn  7763: ol.LC_docs_parameters li:before {
                   7764:   content: "\\002022 \\0020";
                   7765: }
                   7766: 
                   7767: li.LC_docs_parameters_title {
                   7768:   font-weight: bold;
                   7769: }
                   7770: 
                   7771: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7772:   content: "";
                   7773: }
                   7774: 
1.897     wenzelju 7775: ul#LC_secondary_menu {
1.1107    raeburn  7776:   clear: right;
1.911     bisitz   7777:   color: $fontmenu;
                   7778:   background: $tabbg;
                   7779:   list-style: none;
                   7780:   padding: 0;
                   7781:   margin: 0;
                   7782:   width: 100%;
1.995     raeburn  7783:   text-align: left;
1.1107    raeburn  7784:   float: left;
1.808     droeschl 7785: }
                   7786: 
1.897     wenzelju 7787: ul#LC_secondary_menu li {
1.911     bisitz   7788:   font-weight: bold;
                   7789:   line-height: 1.8em;
1.1107    raeburn  7790:   border-right: 1px solid black;
                   7791:   float: left;
                   7792: }
                   7793: 
                   7794: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7795:   background-color: $data_table_light;
                   7796: }
                   7797: 
                   7798: ul#LC_secondary_menu li a {
1.911     bisitz   7799:   padding: 0 0.8em;
1.1107    raeburn  7800: }
                   7801: 
                   7802: ul#LC_secondary_menu li ul {
                   7803:   display: none;
                   7804: }
                   7805: 
                   7806: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7807:   display: block;
                   7808:   position: absolute;
                   7809:   margin: 0;
                   7810:   padding: 0;
                   7811:   list-style:none;
                   7812:   float: none;
                   7813:   background-color: $data_table_light;
                   7814:   z-index: 2;
                   7815:   margin-left: -1px;
                   7816: }
                   7817: 
                   7818: ul#LC_secondary_menu li ul li {
                   7819:   font-size: 90%;
                   7820:   vertical-align: top;
                   7821:   border-left: 1px solid black;
1.911     bisitz   7822:   border-right: 1px solid black;
1.1119    raeburn  7823:   background-color: $data_table_light;
1.1107    raeburn  7824:   list-style:none;
                   7825:   float: none;
                   7826: }
                   7827: 
                   7828: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7829:   background-color: $data_table_dark;
1.807     droeschl 7830: }
                   7831: 
1.847     tempelho 7832: ul.LC_TabContent {
1.911     bisitz   7833:   display:block;
                   7834:   background: $sidebg;
                   7835:   border-bottom: solid 1px $lg_border_color;
                   7836:   list-style:none;
1.1020    raeburn  7837:   margin: -1px -10px 0 -10px;
1.911     bisitz   7838:   padding: 0;
1.693     droeschl 7839: }
                   7840: 
1.795     www      7841: ul.LC_TabContent li,
                   7842: ul.LC_TabContentBigger li {
1.911     bisitz   7843:   float:left;
1.741     harmsja  7844: }
1.795     www      7845: 
1.897     wenzelju 7846: ul#LC_secondary_menu li a {
1.911     bisitz   7847:   color: $fontmenu;
                   7848:   text-decoration: none;
1.693     droeschl 7849: }
1.795     www      7850: 
1.721     harmsja  7851: ul.LC_TabContent {
1.952     onken    7852:   min-height:20px;
1.721     harmsja  7853: }
1.795     www      7854: 
                   7855: ul.LC_TabContent li {
1.911     bisitz   7856:   vertical-align:middle;
1.959     onken    7857:   padding: 0 16px 0 10px;
1.911     bisitz   7858:   background-color:$tabbg;
                   7859:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7860:   border-left: solid 1px $font;
1.721     harmsja  7861: }
1.795     www      7862: 
1.847     tempelho 7863: ul.LC_TabContent .right {
1.911     bisitz   7864:   float:right;
1.847     tempelho 7865: }
                   7866: 
1.911     bisitz   7867: ul.LC_TabContent li a,
                   7868: ul.LC_TabContent li {
                   7869:   color:rgb(47,47,47);
                   7870:   text-decoration:none;
                   7871:   font-size:95%;
                   7872:   font-weight:bold;
1.952     onken    7873:   min-height:20px;
                   7874: }
                   7875: 
1.959     onken    7876: ul.LC_TabContent li a:hover,
                   7877: ul.LC_TabContent li a:focus {
1.952     onken    7878:   color: $button_hover;
1.959     onken    7879:   background:none;
                   7880:   outline:none;
1.952     onken    7881: }
                   7882: 
                   7883: ul.LC_TabContent li:hover {
                   7884:   color: $button_hover;
                   7885:   cursor:pointer;
1.721     harmsja  7886: }
1.795     www      7887: 
1.911     bisitz   7888: ul.LC_TabContent li.active {
1.952     onken    7889:   color: $font;
1.911     bisitz   7890:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7891:   border-bottom:solid 1px #FFFFFF;
                   7892:   cursor: default;
1.744     ehlerst  7893: }
1.795     www      7894: 
1.959     onken    7895: ul.LC_TabContent li.active a {
                   7896:   color:$font;
                   7897:   background:#FFFFFF;
                   7898:   outline: none;
                   7899: }
1.1047    raeburn  7900: 
                   7901: ul.LC_TabContent li.goback {
                   7902:   float: left;
                   7903:   border-left: none;
                   7904: }
                   7905: 
1.870     tempelho 7906: #maincoursedoc {
1.911     bisitz   7907:   clear:both;
1.870     tempelho 7908: }
                   7909: 
                   7910: ul.LC_TabContentBigger {
1.911     bisitz   7911:   display:block;
                   7912:   list-style:none;
                   7913:   padding: 0;
1.870     tempelho 7914: }
                   7915: 
1.795     www      7916: ul.LC_TabContentBigger li {
1.911     bisitz   7917:   vertical-align:bottom;
                   7918:   height: 30px;
                   7919:   font-size:110%;
                   7920:   font-weight:bold;
                   7921:   color: #737373;
1.841     tempelho 7922: }
                   7923: 
1.957     onken    7924: ul.LC_TabContentBigger li.active {
                   7925:   position: relative;
                   7926:   top: 1px;
                   7927: }
                   7928: 
1.870     tempelho 7929: ul.LC_TabContentBigger li a {
1.911     bisitz   7930:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7931:   height: 30px;
                   7932:   line-height: 30px;
                   7933:   text-align: center;
                   7934:   display: block;
                   7935:   text-decoration: none;
1.958     onken    7936:   outline: none;  
1.741     harmsja  7937: }
1.795     www      7938: 
1.870     tempelho 7939: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7940:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7941:   color:$font;
1.744     ehlerst  7942: }
1.795     www      7943: 
1.870     tempelho 7944: ul.LC_TabContentBigger li b {
1.911     bisitz   7945:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7946:   display: block;
                   7947:   float: left;
                   7948:   padding: 0 30px;
1.957     onken    7949:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7950: }
                   7951: 
1.956     onken    7952: ul.LC_TabContentBigger li:hover b {
                   7953:   color:$button_hover;
                   7954: }
                   7955: 
1.870     tempelho 7956: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7957:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7958:   color:$font;
1.957     onken    7959:   border: 0;
1.741     harmsja  7960: }
1.693     droeschl 7961: 
1.870     tempelho 7962: 
1.862     bisitz   7963: ul.LC_CourseBreadcrumbs {
                   7964:   background: $sidebg;
1.1020    raeburn  7965:   height: 2em;
1.862     bisitz   7966:   padding-left: 10px;
1.1020    raeburn  7967:   margin: 0;
1.862     bisitz   7968:   list-style-position: inside;
                   7969: }
                   7970: 
1.911     bisitz   7971: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7972: ol#LC_PathBreadcrumbs {
1.911     bisitz   7973:   padding-left: 10px;
                   7974:   margin: 0;
1.933     droeschl 7975:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7976: }
                   7977: 
1.911     bisitz   7978: ol#LC_MenuBreadcrumbs li,
                   7979: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7980: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7981:   display: inline;
1.933     droeschl 7982:   white-space: normal;  
1.693     droeschl 7983: }
                   7984: 
1.823     bisitz   7985: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7986: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7987:   text-decoration: none;
                   7988:   font-size:90%;
1.693     droeschl 7989: }
1.795     www      7990: 
1.969     droeschl 7991: ol#LC_MenuBreadcrumbs h1 {
                   7992:   display: inline;
                   7993:   font-size: 90%;
                   7994:   line-height: 2.5em;
                   7995:   margin: 0;
                   7996:   padding: 0;
                   7997: }
                   7998: 
1.795     www      7999: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8000:   text-decoration:none;
                   8001:   font-size:100%;
                   8002:   font-weight:bold;
1.693     droeschl 8003: }
1.795     www      8004: 
1.840     bisitz   8005: .LC_Box {
1.911     bisitz   8006:   border: solid 1px $lg_border_color;
                   8007:   padding: 0 10px 10px 10px;
1.746     neumanie 8008: }
1.795     www      8009: 
1.1020    raeburn  8010: .LC_DocsBox {
                   8011:   border: solid 1px $lg_border_color;
                   8012:   padding: 0 0 10px 10px;
                   8013: }
                   8014: 
1.795     www      8015: .LC_AboutMe_Image {
1.911     bisitz   8016:   float:left;
                   8017:   margin-right:10px;
1.747     neumanie 8018: }
1.795     www      8019: 
                   8020: .LC_Clear_AboutMe_Image {
1.911     bisitz   8021:   clear:left;
1.747     neumanie 8022: }
1.795     www      8023: 
1.721     harmsja  8024: dl.LC_ListStyleClean dt {
1.911     bisitz   8025:   padding-right: 5px;
                   8026:   display: table-header-group;
1.693     droeschl 8027: }
                   8028: 
1.721     harmsja  8029: dl.LC_ListStyleClean dd {
1.911     bisitz   8030:   display: table-row;
1.693     droeschl 8031: }
                   8032: 
1.721     harmsja  8033: .LC_ListStyleClean,
                   8034: .LC_ListStyleSimple,
                   8035: .LC_ListStyleNormal,
1.795     www      8036: .LC_ListStyleSpecial {
1.911     bisitz   8037:   /* display:block; */
                   8038:   list-style-position: inside;
                   8039:   list-style-type: none;
                   8040:   overflow: hidden;
                   8041:   padding: 0;
1.693     droeschl 8042: }
                   8043: 
1.721     harmsja  8044: .LC_ListStyleSimple li,
                   8045: .LC_ListStyleSimple dd,
                   8046: .LC_ListStyleNormal li,
                   8047: .LC_ListStyleNormal dd,
                   8048: .LC_ListStyleSpecial li,
1.795     www      8049: .LC_ListStyleSpecial dd {
1.911     bisitz   8050:   margin: 0;
                   8051:   padding: 5px 5px 5px 10px;
                   8052:   clear: both;
1.693     droeschl 8053: }
                   8054: 
1.721     harmsja  8055: .LC_ListStyleClean li,
                   8056: .LC_ListStyleClean dd {
1.911     bisitz   8057:   padding-top: 0;
                   8058:   padding-bottom: 0;
1.693     droeschl 8059: }
                   8060: 
1.721     harmsja  8061: .LC_ListStyleSimple dd,
1.795     www      8062: .LC_ListStyleSimple li {
1.911     bisitz   8063:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8064: }
                   8065: 
1.721     harmsja  8066: .LC_ListStyleSpecial li,
                   8067: .LC_ListStyleSpecial dd {
1.911     bisitz   8068:   list-style-type: none;
                   8069:   background-color: RGB(220, 220, 220);
                   8070:   margin-bottom: 4px;
1.693     droeschl 8071: }
                   8072: 
1.721     harmsja  8073: table.LC_SimpleTable {
1.911     bisitz   8074:   margin:5px;
                   8075:   border:solid 1px $lg_border_color;
1.795     www      8076: }
1.693     droeschl 8077: 
1.721     harmsja  8078: table.LC_SimpleTable tr {
1.911     bisitz   8079:   padding: 0;
                   8080:   border:solid 1px $lg_border_color;
1.693     droeschl 8081: }
1.795     www      8082: 
                   8083: table.LC_SimpleTable thead {
1.911     bisitz   8084:   background:rgb(220,220,220);
1.693     droeschl 8085: }
                   8086: 
1.721     harmsja  8087: div.LC_columnSection {
1.911     bisitz   8088:   display: block;
                   8089:   clear: both;
                   8090:   overflow: hidden;
                   8091:   margin: 0;
1.693     droeschl 8092: }
                   8093: 
1.721     harmsja  8094: div.LC_columnSection>* {
1.911     bisitz   8095:   float: left;
                   8096:   margin: 10px 20px 10px 0;
                   8097:   overflow:hidden;
1.693     droeschl 8098: }
1.721     harmsja  8099: 
1.795     www      8100: table em {
1.911     bisitz   8101:   font-weight: bold;
                   8102:   font-style: normal;
1.748     schulted 8103: }
1.795     www      8104: 
1.779     bisitz   8105: table.LC_tableBrowseRes,
1.795     www      8106: table.LC_tableOfContent {
1.911     bisitz   8107:   border:none;
                   8108:   border-spacing: 1px;
                   8109:   padding: 3px;
                   8110:   background-color: #FFFFFF;
                   8111:   font-size: 90%;
1.753     droeschl 8112: }
1.789     droeschl 8113: 
1.911     bisitz   8114: table.LC_tableOfContent {
                   8115:   border-collapse: collapse;
1.789     droeschl 8116: }
                   8117: 
1.771     droeschl 8118: table.LC_tableBrowseRes a,
1.768     schulted 8119: table.LC_tableOfContent a {
1.911     bisitz   8120:   background-color: transparent;
                   8121:   text-decoration: none;
1.753     droeschl 8122: }
                   8123: 
1.795     www      8124: table.LC_tableOfContent img {
1.911     bisitz   8125:   border: none;
                   8126:   height: 1.3em;
                   8127:   vertical-align: text-bottom;
                   8128:   margin-right: 0.3em;
1.753     droeschl 8129: }
1.757     schulted 8130: 
1.795     www      8131: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8132:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8133: }
                   8134: 
1.795     www      8135: a#LC_content_toolbar_everything {
1.911     bisitz   8136:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8137: }
                   8138: 
1.795     www      8139: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8140:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8141: }
                   8142: 
1.795     www      8143: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8144:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8145: }
                   8146: 
1.795     www      8147: a#LC_content_toolbar_changefolder {
1.911     bisitz   8148:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8149: }
                   8150: 
1.795     www      8151: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8152:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8153: }
                   8154: 
1.1043    raeburn  8155: a#LC_content_toolbar_edittoplevel {
                   8156:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8157: }
                   8158: 
1.795     www      8159: ul#LC_toolbar li a:hover {
1.911     bisitz   8160:   background-position: bottom center;
1.757     schulted 8161: }
                   8162: 
1.795     www      8163: ul#LC_toolbar {
1.911     bisitz   8164:   padding: 0;
                   8165:   margin: 2px;
                   8166:   list-style:none;
                   8167:   position:relative;
                   8168:   background-color:white;
1.1082    raeburn  8169:   overflow: auto;
1.757     schulted 8170: }
                   8171: 
1.795     www      8172: ul#LC_toolbar li {
1.911     bisitz   8173:   border:1px solid white;
                   8174:   padding: 0;
                   8175:   margin: 0;
                   8176:   float: left;
                   8177:   display:inline;
                   8178:   vertical-align:middle;
1.1082    raeburn  8179:   white-space: nowrap;
1.911     bisitz   8180: }
1.757     schulted 8181: 
1.783     amueller 8182: 
1.795     www      8183: a.LC_toolbarItem {
1.911     bisitz   8184:   display:block;
                   8185:   padding: 0;
                   8186:   margin: 0;
                   8187:   height: 32px;
                   8188:   width: 32px;
                   8189:   color:white;
                   8190:   border: none;
                   8191:   background-repeat:no-repeat;
                   8192:   background-color:transparent;
1.757     schulted 8193: }
                   8194: 
1.915     droeschl 8195: ul.LC_funclist {
                   8196:     margin: 0;
                   8197:     padding: 0.5em 1em 0.5em 0;
                   8198: }
                   8199: 
1.933     droeschl 8200: ul.LC_funclist > li:first-child {
                   8201:     font-weight:bold; 
                   8202:     margin-left:0.8em;
                   8203: }
                   8204: 
1.915     droeschl 8205: ul.LC_funclist + ul.LC_funclist {
                   8206:     /* 
                   8207:        left border as a seperator if we have more than
                   8208:        one list 
                   8209:     */
                   8210:     border-left: 1px solid $sidebg;
                   8211:     /* 
                   8212:        this hides the left border behind the border of the 
                   8213:        outer box if element is wrapped to the next 'line' 
                   8214:     */
                   8215:     margin-left: -1px;
                   8216: }
                   8217: 
1.843     bisitz   8218: ul.LC_funclist li {
1.915     droeschl 8219:   display: inline;
1.782     bisitz   8220:   white-space: nowrap;
1.915     droeschl 8221:   margin: 0 0 0 25px;
                   8222:   line-height: 150%;
1.782     bisitz   8223: }
                   8224: 
1.974     wenzelju 8225: .LC_hidden {
                   8226:   display: none;
                   8227: }
                   8228: 
1.1030    www      8229: .LCmodal-overlay {
                   8230: 		position:fixed;
                   8231: 		top:0;
                   8232: 		right:0;
                   8233: 		bottom:0;
                   8234: 		left:0;
                   8235: 		height:100%;
                   8236: 		width:100%;
                   8237: 		margin:0;
                   8238: 		padding:0;
                   8239: 		background:#999;
                   8240: 		opacity:.75;
                   8241: 		filter: alpha(opacity=75);
                   8242: 		-moz-opacity: 0.75;
                   8243: 		z-index:101;
                   8244: }
                   8245: 
                   8246: * html .LCmodal-overlay {   
                   8247: 		position: absolute;
                   8248: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8249: }
                   8250: 
                   8251: .LCmodal-window {
                   8252: 		position:fixed;
                   8253: 		top:50%;
                   8254: 		left:50%;
                   8255: 		margin:0;
                   8256: 		padding:0;
                   8257: 		z-index:102;
                   8258: 	}
                   8259: 
                   8260: * html .LCmodal-window {
                   8261: 		position:absolute;
                   8262: }
                   8263: 
                   8264: .LCclose-window {
                   8265: 		position:absolute;
                   8266: 		width:32px;
                   8267: 		height:32px;
                   8268: 		right:8px;
                   8269: 		top:8px;
                   8270: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8271: 		text-indent:-99999px;
                   8272: 		overflow:hidden;
                   8273: 		cursor:pointer;
                   8274: }
                   8275: 
1.1335    raeburn  8276: pre.LC_wordwrap {
                   8277:   white-space: pre-wrap;
                   8278:   white-space: -moz-pre-wrap;
                   8279:   white-space: -pre-wrap;
                   8280:   white-space: -o-pre-wrap;
                   8281:   word-wrap: break-word;
                   8282: }
                   8283: 
1.1100    raeburn  8284: /*
1.1231    damieng  8285:   styles used for response display
                   8286: */
                   8287: div.LC_radiofoil, div.LC_rankfoil {
                   8288:   margin: .5em 0em .5em 0em;
                   8289: }
                   8290: table.LC_itemgroup {
                   8291:   margin-top: 1em;
                   8292: }
                   8293: 
                   8294: /*
1.1100    raeburn  8295:   styles used by TTH when "Default set of options to pass to tth/m
                   8296:   when converting TeX" in course settings has been set
                   8297: 
                   8298:   option passed: -t
                   8299: 
                   8300: */
                   8301: 
                   8302: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8303: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8304: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8305: td div.norm {line-height:normal;}
                   8306: 
                   8307: /*
                   8308:   option passed -y3
                   8309: */
                   8310: 
                   8311: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8312: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8313: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8314: 
1.1230    damieng  8315: /*
                   8316:   sections with roles, for content only
                   8317: */
                   8318: section[class^="role-"] {
                   8319:   padding-left: 10px;
                   8320:   padding-right: 5px;
                   8321:   margin-top: 8px;
                   8322:   margin-bottom: 8px;
                   8323:   border: 1px solid #2A4;
                   8324:   border-radius: 5px;
                   8325:   box-shadow: 0px 1px 1px #BBB;
                   8326: }
                   8327: section[class^="role-"]>h1 {
                   8328:   position: relative;
                   8329:   margin: 0px;
                   8330:   padding-top: 10px;
                   8331:   padding-left: 40px;
                   8332: }
                   8333: section[class^="role-"]>h1:before {
                   8334:   position: absolute;
                   8335:   left: -5px;
                   8336:   top: 5px;
                   8337: }
                   8338: section.role-activity>h1:before {
                   8339:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8340: }
                   8341: section.role-advice>h1:before {
                   8342:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8343: }
                   8344: section.role-bibliography>h1:before {
                   8345:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8346: }
                   8347: section.role-citation>h1:before {
                   8348:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8349: }
                   8350: section.role-conclusion>h1:before {
                   8351:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8352: }
                   8353: section.role-definition>h1:before {
                   8354:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8355: }
                   8356: section.role-demonstration>h1:before {
                   8357:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8358: }
                   8359: section.role-example>h1:before {
                   8360:   content:url('/adm/daxe/images/section_icons/example.png');
                   8361: }
                   8362: section.role-explanation>h1:before {
                   8363:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8364: }
                   8365: section.role-introduction>h1:before {
                   8366:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8367: }
                   8368: section.role-method>h1:before {
                   8369:   content:url('/adm/daxe/images/section_icons/method.png');
                   8370: }
                   8371: section.role-more_information>h1:before {
                   8372:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8373: }
                   8374: section.role-objectives>h1:before {
                   8375:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8376: }
                   8377: section.role-prerequisites>h1:before {
                   8378:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8379: }
                   8380: section.role-remark>h1:before {
                   8381:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8382: }
                   8383: section.role-reminder>h1:before {
                   8384:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8385: }
                   8386: section.role-summary>h1:before {
                   8387:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8388: }
                   8389: section.role-syntax>h1:before {
                   8390:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8391: }
                   8392: section.role-warning>h1:before {
                   8393:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8394: }
                   8395: 
1.1269    raeburn  8396: #LC_minitab_header {
                   8397:   float:left;
                   8398:   width:100%;
                   8399:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8400:   font-size:93%;
                   8401:   line-height:normal;
                   8402:   margin: 0.5em 0 0.5em 0;
                   8403: }
                   8404: #LC_minitab_header ul {
                   8405:   margin:0;
                   8406:   padding:10px 10px 0;
                   8407:   list-style:none;
                   8408: }
                   8409: #LC_minitab_header li {
                   8410:   float:left;
                   8411:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8412:   margin:0;
                   8413:   padding:0 0 0 9px;
                   8414: }
                   8415: #LC_minitab_header a {
                   8416:   display:block;
                   8417:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8418:   padding:5px 15px 4px 6px;
                   8419: }
                   8420: #LC_minitab_header #LC_current_minitab {
                   8421:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8422: }
                   8423: #LC_minitab_header #LC_current_minitab a {
                   8424:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8425:   padding-bottom:5px;
                   8426: }
                   8427: 
                   8428: 
1.343     albertel 8429: END
                   8430: }
                   8431: 
1.306     albertel 8432: =pod
                   8433: 
                   8434: =item * &headtag()
                   8435: 
                   8436: Returns a uniform footer for LON-CAPA web pages.
                   8437: 
1.307     albertel 8438: Inputs: $title - optional title for the head
                   8439:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8440:         $args - optional arguments
1.319     albertel 8441:             force_register - if is true call registerurl so the remote is 
                   8442:                              informed
1.415     albertel 8443:             redirect       -> array ref of
                   8444:                                    1- seconds before redirect occurs
                   8445:                                    2- url to redirect to
                   8446:                                    3- whether the side effect should occur
1.315     albertel 8447:                            (side effect of setting 
                   8448:                                $env{'internal.head.redirect'} to the url 
                   8449:                                redirected too)
1.352     albertel 8450:             domain         -> force to color decorate a page for a specific
                   8451:                                domain
                   8452:             function       -> force usage of a specific rolish color scheme
                   8453:             bgcolor        -> override the default page bgcolor
1.460     albertel 8454:             no_auto_mt_title
                   8455:                            -> prevent &mt()ing the title arg
1.464     albertel 8456: 
1.306     albertel 8457: =cut
                   8458: 
                   8459: sub headtag {
1.313     albertel 8460:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8461:     
1.363     albertel 8462:     my $function = $args->{'function'} || &get_users_function();
                   8463:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8464:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8465:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8466:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8467: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8468: 		   #time(),
1.418     albertel 8469: 		   $env{'environment.color.timestamp'},
1.363     albertel 8470: 		   $function,$domain,$bgcolor);
                   8471: 
1.369     www      8472:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8473: 
1.308     albertel 8474:     my $result =
                   8475: 	'<head>'.
1.1160    raeburn  8476: 	&font_settings($args);
1.319     albertel 8477: 
1.1188    raeburn  8478:     my $inhibitprint;
                   8479:     if ($args->{'print_suppress'}) {
                   8480:         $inhibitprint = &print_suppression();
                   8481:     }
1.1064    raeburn  8482: 
1.461     albertel 8483:     if (!$args->{'frameset'}) {
                   8484: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8485:     }
1.962     droeschl 8486:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8487:         $result .= Apache::lonxml::display_title();
1.319     albertel 8488:     }
1.436     albertel 8489:     if (!$args->{'no_nav_bar'} 
                   8490: 	&& !$args->{'only_body'}
                   8491: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8492: 	$result .= &help_menu_js($httphost);
1.1032    www      8493:         $result.=&modal_window();
1.1038    www      8494:         $result.=&togglebox_script();
1.1034    www      8495:         $result.=&wishlist_window();
1.1041    www      8496:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8497:     } else {
                   8498:         if ($args->{'add_modal'}) {
                   8499:            $result.=&modal_window();
                   8500:         }
                   8501:         if ($args->{'add_wishlist'}) {
                   8502:            $result.=&wishlist_window();
                   8503:         }
1.1038    www      8504:         if ($args->{'add_togglebox'}) {
                   8505:            $result.=&togglebox_script();
                   8506:         }
1.1041    www      8507:         if ($args->{'add_progressbar'}) {
                   8508:            $result.=&LCprogressbarUpdate_script();
                   8509:         }
1.436     albertel 8510:     }
1.314     albertel 8511:     if (ref($args->{'redirect'})) {
1.414     albertel 8512: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8513: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8514: 	if (!$inhibit_continue) {
                   8515: 	    $env{'internal.head.redirect'} = $url;
                   8516: 	}
1.313     albertel 8517: 	$result.=<<ADDMETA
                   8518: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8519: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8520: ADDMETA
1.1210    raeburn  8521:     } else {
                   8522:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8523:             my $requrl = $env{'request.uri'};
                   8524:             if ($requrl eq '') {
                   8525:                 $requrl = $ENV{'REQUEST_URI'};
                   8526:                 $requrl =~ s/\?.+$//;
                   8527:             }
                   8528:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8529:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8530:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8531:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8532:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8533:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8534:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8535:                     my $offload;
1.1210    raeburn  8536:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8537:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8538:                             $offload = 1;
                   8539:                         }
                   8540:                     }
                   8541:                     unless ($offload) {
                   8542:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8543:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8544:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8545:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8546:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8547:                                         $offload = 1;
                   8548:                                         $dom_in_use = $env{'user.domain'};
                   8549:                                     }
1.1210    raeburn  8550:                                 }
1.1340    raeburn  8551:                             }
                   8552:                         }
                   8553:                     }
                   8554:                     if ($offload) {
                   8555:                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8556:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8557:                             my $numsec = 5;
                   8558:                             my $timeout = $numsec * 1000;
                   8559:                             my ($newurl,$locknum,%locks,$msg);
                   8560:                             if ($env{'request.role.adv'}) {
                   8561:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8562:                             }
                   8563:                             my $disable_submit = 0;
                   8564:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8565:                                 $disable_submit = 1;
                   8566:                             }
                   8567:                             if ($locknum) {
                   8568:                                 my @lockinfo = sort(values(%locks));
                   8569:                                 $msg = &mt('Once the following tasks are complete: ')."\n".
                   8570:                                        join(", ",sort(values(%locks)))."\n";
                   8571:                                 if (&show_course()) {
                   8572:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8573:                                 } else {
                   8574:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8575:                                 }
1.1340    raeburn  8576:                             } else {
                   8577:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8578:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8579:                                 }
                   8580:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8581:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8582:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8583:                                     $newurl .= '&role='.$env{'request.role'};
                   8584:                                 }
                   8585:                                 if ($env{'request.symb'}) {
                   8586:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8587:                                     if ($shownsymb =~ m{^/enc/}) {
                   8588:                                         my $reqdmajor = 2;
                   8589:                                         my $reqdminor = 11;
                   8590:                                         my $reqdsubminor = 3;
                   8591:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8592:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8593:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8594:                                         if (($major eq '' && $minor eq '') ||
                   8595:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8596:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8597:                                              ($reqdsubminor > $subminor))))) {
                   8598:                                             undef($shownsymb);
                   8599:                                         }
1.1210    raeburn  8600:                                     }
1.1340    raeburn  8601:                                     if ($shownsymb) {
                   8602:                                         &js_escape(\$shownsymb);
                   8603:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  8604:                                     }
1.1340    raeburn  8605:                                 } else {
                   8606:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8607:                                     &js_escape(\$shownurl);
                   8608:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  8609:                                 }
1.1340    raeburn  8610:                             }
                   8611:                             &js_escape(\$msg);
                   8612:                             $result.=<<OFFLOAD
1.1210    raeburn  8613: <meta http-equiv="pragma" content="no-cache" />
                   8614: <script type="text/javascript">
1.1215    raeburn  8615: // <![CDATA[
1.1210    raeburn  8616: function LC_Offload_Now() {
                   8617:     var dest = "$newurl";
                   8618:     if (dest != '') {
                   8619:         window.location.href="$newurl";
                   8620:     }
                   8621: }
1.1214    raeburn  8622: \$(document).ready(function () {
                   8623:     window.alert('$msg');
                   8624:     if ($disable_submit) {
1.1210    raeburn  8625:         \$(".LC_hwk_submit").prop("disabled", true);
                   8626:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8627:     }
                   8628:     setTimeout('LC_Offload_Now()', $timeout);
                   8629: });
1.1215    raeburn  8630: // ]]>
1.1210    raeburn  8631: </script>
                   8632: OFFLOAD
                   8633:                         }
                   8634:                     }
                   8635:                 }
                   8636:             }
                   8637:         }
1.313     albertel 8638:     }
1.306     albertel 8639:     if (!defined($title)) {
                   8640: 	$title = 'The LearningOnline Network with CAPA';
                   8641:     }
1.460     albertel 8642:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8643:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8644: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8645:     if (!$args->{'frameset'}) {
                   8646:         $result .= ' /';
                   8647:     }
                   8648:     $result .= '>' 
1.1064    raeburn  8649:         .$inhibitprint
1.414     albertel 8650: 	.$head_extra;
1.1242    raeburn  8651:     my $clientmobile;
                   8652:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8653:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8654:     } else {
                   8655:         $clientmobile = $env{'browser.mobile'};
                   8656:     }
                   8657:     if ($clientmobile) {
1.1137    raeburn  8658:         $result .= '
                   8659: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8660: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8661:     }
1.1278    raeburn  8662:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8663:     return $result.'</head>';
1.306     albertel 8664: }
                   8665: 
                   8666: =pod
                   8667: 
1.340     albertel 8668: =item * &font_settings()
                   8669: 
                   8670: Returns neccessary <meta> to set the proper encoding
                   8671: 
1.1160    raeburn  8672: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8673: 
                   8674: =cut
                   8675: 
                   8676: sub font_settings {
1.1160    raeburn  8677:     my ($args) = @_;
1.340     albertel 8678:     my $headerstring='';
1.1160    raeburn  8679:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8680:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8681:         $headerstring.=
                   8682:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8683:         if (!$args->{'frameset'}) {
                   8684: 	    $headerstring.= ' /';
                   8685:         }
                   8686: 	$headerstring .= '>'."\n";
1.340     albertel 8687:     }
                   8688:     return $headerstring;
                   8689: }
                   8690: 
1.341     albertel 8691: =pod
                   8692: 
1.1064    raeburn  8693: =item * &print_suppression()
                   8694: 
                   8695: In course context returns css which causes the body to be blank when media="print",
                   8696: if printout generation is unavailable for the current resource.
                   8697: 
                   8698: This could be because:
                   8699: 
                   8700: (a) printstartdate is in the future
                   8701: 
                   8702: (b) printenddate is in the past
                   8703: 
                   8704: (c) there is an active exam block with "printout"
                   8705: functionality blocked
                   8706: 
                   8707: Users with pav, pfo or evb privileges are exempt.
                   8708: 
                   8709: Inputs: none
                   8710: 
                   8711: =cut
                   8712: 
                   8713: 
                   8714: sub print_suppression {
                   8715:     my $noprint;
                   8716:     if ($env{'request.course.id'}) {
                   8717:         my $scope = $env{'request.course.id'};
                   8718:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8719:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8720:             return;
                   8721:         }
                   8722:         if ($env{'request.course.sec'} ne '') {
                   8723:             $scope .= "/$env{'request.course.sec'}";
                   8724:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8725:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8726:                 return;
1.1064    raeburn  8727:             }
                   8728:         }
                   8729:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8730:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8731:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8732:         if ($blocked) {
                   8733:             my $checkrole = "cm./$cdom/$cnum";
                   8734:             if ($env{'request.course.sec'} ne '') {
                   8735:                 $checkrole .= "/$env{'request.course.sec'}";
                   8736:             }
                   8737:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8738:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8739:                 $noprint = 1;
                   8740:             }
                   8741:         }
                   8742:         unless ($noprint) {
                   8743:             my $symb = &Apache::lonnet::symbread();
                   8744:             if ($symb ne '') {
                   8745:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8746:                 if (ref($navmap)) {
                   8747:                     my $res = $navmap->getBySymb($symb);
                   8748:                     if (ref($res)) {
                   8749:                         if (!$res->resprintable()) {
                   8750:                             $noprint = 1;
                   8751:                         }
                   8752:                     }
                   8753:                 }
                   8754:             }
                   8755:         }
                   8756:         if ($noprint) {
                   8757:             return <<"ENDSTYLE";
                   8758: <style type="text/css" media="print">
                   8759:     body { display:none }
                   8760: </style>
                   8761: ENDSTYLE
                   8762:         }
                   8763:     }
                   8764:     return;
                   8765: }
                   8766: 
                   8767: =pod
                   8768: 
1.341     albertel 8769: =item * &xml_begin()
                   8770: 
                   8771: Returns the needed doctype and <html>
                   8772: 
                   8773: Inputs: none
                   8774: 
                   8775: =cut
                   8776: 
                   8777: sub xml_begin {
1.1168    raeburn  8778:     my ($is_frameset) = @_;
1.341     albertel 8779:     my $output='';
                   8780: 
                   8781:     if ($env{'browser.mathml'}) {
                   8782: 	$output='<?xml version="1.0"?>'
                   8783:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8784: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8785:             
                   8786: #	    .'<!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">] >'
                   8787: 	    .'<!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">'
                   8788:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8789: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8790:     } elsif ($is_frameset) {
                   8791:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8792:                 '<html>'."\n";
1.341     albertel 8793:     } else {
1.1168    raeburn  8794: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8795:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8796:     }
                   8797:     return $output;
                   8798: }
1.340     albertel 8799: 
                   8800: =pod
                   8801: 
1.306     albertel 8802: =item * &start_page()
                   8803: 
                   8804: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8805: 
1.648     raeburn  8806: Inputs:
                   8807: 
                   8808: =over 4
                   8809: 
                   8810: $title - optional title for the page
                   8811: 
                   8812: $head_extra - optional extra HTML to incude inside the <head>
                   8813: 
                   8814: $args - additional optional args supported are:
                   8815: 
                   8816: =over 8
                   8817: 
                   8818:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8819:                                     arg on
1.814     bisitz   8820:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8821:              add_entries    -> additional attributes to add to the  <body>
                   8822:              domain         -> force to color decorate a page for a 
1.317     albertel 8823:                                     specific domain
1.648     raeburn  8824:              function       -> force usage of a specific rolish color
1.317     albertel 8825:                                     scheme
1.648     raeburn  8826:              redirect       -> see &headtag()
                   8827:              bgcolor        -> override the default page bg color
                   8828:              js_ready       -> return a string ready for being used in 
1.317     albertel 8829:                                     a javascript writeln
1.648     raeburn  8830:              html_encode    -> return a string ready for being used in 
1.320     albertel 8831:                                     a html attribute
1.648     raeburn  8832:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8833:                                     $forcereg arg
1.648     raeburn  8834:              frameset       -> if true will start with a <frameset>
1.330     albertel 8835:                                     rather than <body>
1.648     raeburn  8836:              skip_phases    -> hash ref of 
1.338     albertel 8837:                                     head -> skip the <html><head> generation
                   8838:                                     body -> skip all <body> generation
1.648     raeburn  8839:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8840:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8841:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8842:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8843:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8844:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8845:                                specific group
                   8846:              use_absolute   -> for request for external resource or syllabus, this
                   8847:                                will contain https://<hostname> if server uses
                   8848:                                https (as per hosts.tab), but request is for http
                   8849:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8850: 
1.648     raeburn  8851: =back
1.460     albertel 8852: 
1.648     raeburn  8853: =back
1.562     albertel 8854: 
1.306     albertel 8855: =cut
                   8856: 
                   8857: sub start_page {
1.309     albertel 8858:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8859:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8860: 
1.315     albertel 8861:     $env{'internal.start_page'}++;
1.1318    raeburn  8862:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu);
1.964     droeschl 8863: 
1.338     albertel 8864:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8865:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8866:     }
1.1316    raeburn  8867: 
                   8868:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  8869:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8870:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8871:                 $args->{'no_primary_menu'} = 1;
                   8872:             }
                   8873:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8874:                 $args->{'no_inline_menu'} = 1;
                   8875:             }
                   8876:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8877:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8878:             }
                   8879:         } else {
                   8880:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8881:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8882:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8883:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8884:                     $args->{'no_primary_menu'} = 1;
                   8885:                 }
                   8886:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8887:                     $args->{'no_inline_menu'} = 1;
                   8888:                 }
                   8889:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8890:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8891:                 }
                   8892:             }
                   8893:         }
1.1316    raeburn  8894:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8895:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8896:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8897:     }
1.338     albertel 8898:     
                   8899:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8900: 	if ($args->{'frameset'}) {
                   8901: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8902: 						$args->{'add_entries'});
                   8903: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8904:         } else {
                   8905:             $result .=
                   8906:                 &bodytag($title, 
                   8907:                          $args->{'function'},       $args->{'add_entries'},
                   8908:                          $args->{'only_body'},      $args->{'domain'},
                   8909:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8910:                          $args->{'bgcolor'},        $args,
1.1318    raeburn  8911:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu);
1.831     bisitz   8912:         }
1.330     albertel 8913:     }
1.338     albertel 8914: 
1.315     albertel 8915:     if ($args->{'js_ready'}) {
1.713     kaisler  8916: 		$result = &js_ready($result);
1.315     albertel 8917:     }
1.320     albertel 8918:     if ($args->{'html_encode'}) {
1.713     kaisler  8919: 		$result = &html_encode($result);
                   8920:     }
                   8921: 
1.813     bisitz   8922:     # Preparation for new and consistent functionlist at top of screen
                   8923:     # if ($args->{'functionlist'}) {
                   8924:     #            $result .= &build_functionlist();
                   8925:     #}
                   8926: 
1.964     droeschl 8927:     # Don't add anything more if only_body wanted or in const space
                   8928:     return $result if    $args->{'only_body'} 
                   8929:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8930: 
                   8931:     #Breadcrumbs
1.758     kaisler  8932:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8933: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8934: 		#if any br links exists, add them to the breadcrumbs
                   8935: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8936: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8937: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8938: 			}
                   8939: 		}
1.1096    raeburn  8940:                 # if @advtools array contains items add then to the breadcrumbs
                   8941:                 if (@advtools > 0) {
                   8942:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8943:                 }
1.1272    raeburn  8944:                 my $menulink;
                   8945:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8946:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  8947:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  8948:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8949:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8950:                      (!$env{'request.role.adv'}))) {
                   8951:                     $menulink = 0;
                   8952:                 } else {
                   8953:                     undef($menulink);
                   8954:                 }
1.758     kaisler  8955: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8956: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8957: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8958:                 } else {
1.1272    raeburn  8959: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8960: 		}
1.320     albertel 8961:     }
1.315     albertel 8962:     return $result;
1.306     albertel 8963: }
                   8964: 
                   8965: sub end_page {
1.315     albertel 8966:     my ($args) = @_;
                   8967:     $env{'internal.end_page'}++;
1.330     albertel 8968:     my $result;
1.335     albertel 8969:     if ($args->{'discussion'}) {
                   8970: 	my ($target,$parser);
                   8971: 	if (ref($args->{'discussion'})) {
                   8972: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8973: 				$args->{'discussion'}{'parser'});
                   8974: 	}
                   8975: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8976:     }
1.330     albertel 8977:     if ($args->{'frameset'}) {
                   8978: 	$result .= '</frameset>';
                   8979:     } else {
1.635     raeburn  8980: 	$result .= &endbodytag($args);
1.330     albertel 8981:     }
1.1080    raeburn  8982:     unless ($args->{'notbody'}) {
                   8983:         $result .= "\n</html>";
                   8984:     }
1.330     albertel 8985: 
1.315     albertel 8986:     if ($args->{'js_ready'}) {
1.317     albertel 8987: 	$result = &js_ready($result);
1.315     albertel 8988:     }
1.335     albertel 8989: 
1.320     albertel 8990:     if ($args->{'html_encode'}) {
                   8991: 	$result = &html_encode($result);
                   8992:     }
1.335     albertel 8993: 
1.315     albertel 8994:     return $result;
                   8995: }
                   8996: 
1.1034    www      8997: sub wishlist_window {
                   8998:     return(<<'ENDWISHLIST');
1.1046    raeburn  8999: <script type="text/javascript">
1.1034    www      9000: // <![CDATA[
                   9001: // <!-- BEGIN LON-CAPA Internal
                   9002: function set_wishlistlink(title, path) {
                   9003:     if (!title) {
                   9004:         title = document.title;
                   9005:         title = title.replace(/^LON-CAPA /,'');
                   9006:     }
1.1175    raeburn  9007:     title = encodeURIComponent(title);
1.1203    raeburn  9008:     title = title.replace("'","\\\'");
1.1034    www      9009:     if (!path) {
                   9010:         path = location.pathname;
                   9011:     }
1.1175    raeburn  9012:     path = encodeURIComponent(path);
1.1203    raeburn  9013:     path = path.replace("'","\\\'");
1.1034    www      9014:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9015:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9016: }
                   9017: // END LON-CAPA Internal -->
                   9018: // ]]>
                   9019: </script>
                   9020: ENDWISHLIST
                   9021: }
                   9022: 
1.1030    www      9023: sub modal_window {
                   9024:     return(<<'ENDMODAL');
1.1046    raeburn  9025: <script type="text/javascript">
1.1030    www      9026: // <![CDATA[
                   9027: // <!-- BEGIN LON-CAPA Internal
                   9028: var modalWindow = {
                   9029: 	parent:"body",
                   9030: 	windowId:null,
                   9031: 	content:null,
                   9032: 	width:null,
                   9033: 	height:null,
                   9034: 	close:function()
                   9035: 	{
                   9036: 	        $(".LCmodal-window").remove();
                   9037: 	        $(".LCmodal-overlay").remove();
                   9038: 	},
                   9039: 	open:function()
                   9040: 	{
                   9041: 		var modal = "";
                   9042: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9043: 		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;\">";
                   9044: 		modal += this.content;
                   9045: 		modal += "</div>";	
                   9046: 
                   9047: 		$(this.parent).append(modal);
                   9048: 
                   9049: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9050: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9051: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9052: 	}
                   9053: };
1.1140    raeburn  9054: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9055: 	{
1.1266    raeburn  9056:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9057: 		modalWindow.windowId = "myModal";
                   9058: 		modalWindow.width = width;
                   9059: 		modalWindow.height = height;
1.1196    raeburn  9060: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9061: 		modalWindow.open();
1.1208    raeburn  9062: 	};
1.1030    www      9063: // END LON-CAPA Internal -->
                   9064: // ]]>
                   9065: </script>
                   9066: ENDMODAL
                   9067: }
                   9068: 
                   9069: sub modal_link {
1.1140    raeburn  9070:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9071:     unless ($width) { $width=480; }
                   9072:     unless ($height) { $height=400; }
1.1031    www      9073:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9074:     unless ($transparency) { $transparency='true'; }
                   9075: 
1.1074    raeburn  9076:     my $target_attr;
                   9077:     if (defined($target)) {
                   9078:         $target_attr = 'target="'.$target.'"';
                   9079:     }
                   9080:     return <<"ENDLINK";
1.1336    raeburn  9081: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9082: ENDLINK
1.1030    www      9083: }
                   9084: 
1.1032    www      9085: sub modal_adhoc_script {
                   9086:     my ($funcname,$width,$height,$content)=@_;
                   9087:     return (<<ENDADHOC);
1.1046    raeburn  9088: <script type="text/javascript">
1.1032    www      9089: // <![CDATA[
                   9090:         var $funcname = function()
                   9091:         {
                   9092:                 modalWindow.windowId = "myModal";
                   9093:                 modalWindow.width = $width;
                   9094:                 modalWindow.height = $height;
                   9095:                 modalWindow.content = '$content';
                   9096:                 modalWindow.open();
                   9097:         };  
                   9098: // ]]>
                   9099: </script>
                   9100: ENDADHOC
                   9101: }
                   9102: 
1.1041    www      9103: sub modal_adhoc_inner {
                   9104:     my ($funcname,$width,$height,$content)=@_;
                   9105:     my $innerwidth=$width-20;
                   9106:     $content=&js_ready(
1.1140    raeburn  9107:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9108:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9109:                  $content.
1.1041    www      9110:                  &end_scrollbox().
1.1140    raeburn  9111:                  &end_page()
1.1041    www      9112:              );
                   9113:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   9114: }
                   9115: 
                   9116: sub modal_adhoc_window {
                   9117:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   9118:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   9119:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9120: }
                   9121: 
                   9122: sub modal_adhoc_launch {
                   9123:     my ($funcname,$width,$height,$content)=@_;
                   9124:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9125: <script type="text/javascript">
                   9126: // <![CDATA[
                   9127: $funcname();
                   9128: // ]]>
                   9129: </script>
                   9130: ENDLAUNCH
                   9131: }
                   9132: 
                   9133: sub modal_adhoc_close {
                   9134:     return (<<ENDCLOSE);
                   9135: <script type="text/javascript">
                   9136: // <![CDATA[
                   9137: modalWindow.close();
                   9138: // ]]>
                   9139: </script>
                   9140: ENDCLOSE
                   9141: }
                   9142: 
1.1038    www      9143: sub togglebox_script {
                   9144:    return(<<ENDTOGGLE);
                   9145: <script type="text/javascript"> 
                   9146: // <![CDATA[
                   9147: function LCtoggleDisplay(id,hidetext,showtext) {
                   9148:    link = document.getElementById(id + "link").childNodes[0];
                   9149:    with (document.getElementById(id).style) {
                   9150:       if (display == "none" ) {
                   9151:           display = "inline";
                   9152:           link.nodeValue = hidetext;
                   9153:         } else {
                   9154:           display = "none";
                   9155:           link.nodeValue = showtext;
                   9156:        }
                   9157:    }
                   9158: }
                   9159: // ]]>
                   9160: </script>
                   9161: ENDTOGGLE
                   9162: }
                   9163: 
1.1039    www      9164: sub start_togglebox {
                   9165:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9166:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9167:     unless ($showtext) { $showtext=&mt('show'); }
                   9168:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9169:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9170:     return &start_data_table().
                   9171:            &start_data_table_header_row().
                   9172:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9173:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9174:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9175:            &end_data_table_header_row().
                   9176:            '<tr id="'.$id.'" style="display:none""><td>';
                   9177: }
                   9178: 
                   9179: sub end_togglebox {
                   9180:     return '</td></tr>'.&end_data_table();
                   9181: }
                   9182: 
1.1041    www      9183: sub LCprogressbar_script {
1.1302    raeburn  9184:    my ($id,$number_to_do)=@_;
                   9185:    if ($number_to_do) {
                   9186:        return(<<ENDPROGRESS);
1.1041    www      9187: <script type="text/javascript">
                   9188: // <![CDATA[
1.1045    www      9189: \$('#progressbar$id').progressbar({
1.1041    www      9190:   value: 0,
                   9191:   change: function(event, ui) {
                   9192:     var newVal = \$(this).progressbar('option', 'value');
                   9193:     \$('.pblabel', this).text(LCprogressTxt);
                   9194:   }
                   9195: });
                   9196: // ]]>
                   9197: </script>
                   9198: ENDPROGRESS
1.1302    raeburn  9199:    } else {
                   9200:        return(<<ENDPROGRESS);
                   9201: <script type="text/javascript">
                   9202: // <![CDATA[
                   9203: \$('#progressbar$id').progressbar({
                   9204:   value: false,
                   9205:   create: function(event, ui) {
                   9206:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9207:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9208:   }
                   9209: });
                   9210: // ]]>
                   9211: </script>
                   9212: ENDPROGRESS
                   9213:    }
1.1041    www      9214: }
                   9215: 
                   9216: sub LCprogressbarUpdate_script {
                   9217:    return(<<ENDPROGRESSUPDATE);
                   9218: <style type="text/css">
                   9219: .ui-progressbar { position:relative; }
1.1302    raeburn  9220: .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      9221: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9222: </style>
                   9223: <script type="text/javascript">
                   9224: // <![CDATA[
1.1045    www      9225: var LCprogressTxt='---';
                   9226: 
1.1302    raeburn  9227: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9228:    LCprogressTxt=progresstext;
1.1302    raeburn  9229:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9230:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9231:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9232:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9233:    } else {
                   9234:        \$('#progressbar'+id).progressbar('value',percent);
                   9235:    }
1.1041    www      9236: }
                   9237: // ]]>
                   9238: </script>
                   9239: ENDPROGRESSUPDATE
                   9240: }
                   9241: 
1.1042    www      9242: my $LClastpercent;
1.1045    www      9243: my $LCidcnt;
                   9244: my $LCcurrentid;
1.1042    www      9245: 
1.1041    www      9246: sub LCprogressbar {
1.1302    raeburn  9247:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9248:     $LClastpercent=0;
1.1045    www      9249:     $LCidcnt++;
                   9250:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9251:     my ($starting,$content);
                   9252:     if ($number_to_do) {
                   9253:         $starting=&mt('Starting');
                   9254:         $content=(<<ENDPROGBAR);
                   9255: $preamble
1.1045    www      9256:   <div id="progressbar$LCcurrentid">
1.1041    www      9257:     <span class="pblabel">$starting</span>
                   9258:   </div>
                   9259: ENDPROGBAR
1.1302    raeburn  9260:     } else {
                   9261:         $starting=&mt('Loading...');
                   9262:         $LClastpercent='false';
                   9263:         $content=(<<ENDPROGBAR);
                   9264: $preamble
                   9265:   <div id="progressbar$LCcurrentid">
                   9266:       <div class="progress-label">$starting</div>
                   9267:   </div>
                   9268: ENDPROGBAR
                   9269:     }
                   9270:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9271: }
                   9272: 
                   9273: sub LCprogressbarUpdate {
1.1302    raeburn  9274:     my ($r,$val,$text,$number_to_do)=@_;
                   9275:     if ($number_to_do) {
                   9276:         unless ($val) { 
                   9277:             if ($LClastpercent) {
                   9278:                 $val=$LClastpercent;
                   9279:             } else {
                   9280:                 $val=0;
                   9281:             }
                   9282:         }
                   9283:         if ($val<0) { $val=0; }
                   9284:         if ($val>100) { $val=0; }
                   9285:         $LClastpercent=$val;
                   9286:         unless ($text) { $text=$val.'%'; }
                   9287:     } else {
                   9288:         $val = 'false';
1.1042    www      9289:     }
1.1041    www      9290:     $text=&js_ready($text);
1.1044    www      9291:     &r_print($r,<<ENDUPDATE);
1.1041    www      9292: <script type="text/javascript">
                   9293: // <![CDATA[
1.1302    raeburn  9294: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9295: // ]]>
                   9296: </script>
                   9297: ENDUPDATE
1.1035    www      9298: }
                   9299: 
1.1042    www      9300: sub LCprogressbarClose {
                   9301:     my ($r)=@_;
                   9302:     $LClastpercent=0;
1.1044    www      9303:     &r_print($r,<<ENDCLOSE);
1.1042    www      9304: <script type="text/javascript">
                   9305: // <![CDATA[
1.1045    www      9306: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9307: // ]]>
                   9308: </script>
                   9309: ENDCLOSE
1.1044    www      9310: }
                   9311: 
                   9312: sub r_print {
                   9313:     my ($r,$to_print)=@_;
                   9314:     if ($r) {
                   9315:       $r->print($to_print);
                   9316:       $r->rflush();
                   9317:     } else {
                   9318:       print($to_print);
                   9319:     }
1.1042    www      9320: }
                   9321: 
1.320     albertel 9322: sub html_encode {
                   9323:     my ($result) = @_;
                   9324: 
1.322     albertel 9325:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9326:     
                   9327:     return $result;
                   9328: }
1.1044    www      9329: 
1.317     albertel 9330: sub js_ready {
                   9331:     my ($result) = @_;
                   9332: 
1.323     albertel 9333:     $result =~ s/[\n\r]/ /xmsg;
                   9334:     $result =~ s/\\/\\\\/xmsg;
                   9335:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9336:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9337:     
                   9338:     return $result;
                   9339: }
                   9340: 
1.315     albertel 9341: sub validate_page {
                   9342:     if (  exists($env{'internal.start_page'})
1.316     albertel 9343: 	  &&     $env{'internal.start_page'} > 1) {
                   9344: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9345: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9346: 				 $ENV{'request.filename'});
1.315     albertel 9347:     }
                   9348:     if (  exists($env{'internal.end_page'})
1.316     albertel 9349: 	  &&     $env{'internal.end_page'} > 1) {
                   9350: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9351: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9352: 				 $env{'request.filename'});
1.315     albertel 9353:     }
                   9354:     if (     exists($env{'internal.start_page'})
                   9355: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9356: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9357: 				 $env{'request.filename'});
1.315     albertel 9358:     }
                   9359:     if (   ! exists($env{'internal.start_page'})
                   9360: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9361: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9362: 				 $env{'request.filename'});
1.315     albertel 9363:     }
1.306     albertel 9364: }
1.315     albertel 9365: 
1.996     www      9366: 
                   9367: sub start_scrollbox {
1.1140    raeburn  9368:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9369:     unless ($outerwidth) { $outerwidth='520px'; }
                   9370:     unless ($width) { $width='500px'; }
                   9371:     unless ($height) { $height='200px'; }
1.1075    raeburn  9372:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9373:     if ($id ne '') {
1.1140    raeburn  9374:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9375:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9376:     }
1.1075    raeburn  9377:     if ($bgcolor ne '') {
                   9378:         $tdcol = "background-color: $bgcolor;";
                   9379:     }
1.1137    raeburn  9380:     my $nicescroll_js;
                   9381:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9382:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9383:     }
                   9384:     return <<"END";
                   9385: $nicescroll_js
                   9386: 
                   9387: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9388: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9389: END
                   9390: }
                   9391: 
                   9392: sub end_scrollbox {
                   9393:     return '</div></td></tr></table>';
                   9394: }
                   9395: 
                   9396: sub nicescroll_javascript {
                   9397:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9398:     my %options;
                   9399:     if (ref($cursor) eq 'HASH') {
                   9400:         %options = %{$cursor};
                   9401:     }
                   9402:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9403:         $options{'railalign'} = 'left';
                   9404:     }
                   9405:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9406:         my $function  = &get_users_function();
                   9407:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9408:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9409:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9410:         }
1.1140    raeburn  9411:     }
                   9412:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9413:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9414:             $options{'cursoropacity'}='1.0';
                   9415:         }
1.1140    raeburn  9416:     } else {
                   9417:         $options{'cursoropacity'}='1.0';
                   9418:     }
                   9419:     if ($options{'cursorfixedheight'} eq 'none') {
                   9420:         delete($options{'cursorfixedheight'});
                   9421:     } else {
                   9422:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9423:     }
                   9424:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9425:         delete($options{'railoffset'});
                   9426:     }
                   9427:     my @niceoptions;
                   9428:     while (my($key,$value) = each(%options)) {
                   9429:         if ($value =~ /^\{.+\}$/) {
                   9430:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9431:         } else {
1.1140    raeburn  9432:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9433:         }
1.1140    raeburn  9434:     }
                   9435:     my $nicescroll_js = '
1.1137    raeburn  9436: $(document).ready(
1.1140    raeburn  9437:       function() {
                   9438:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9439:       }
1.1137    raeburn  9440: );
                   9441: ';
1.1140    raeburn  9442:     if ($framecheck) {
                   9443:         $nicescroll_js .= '
                   9444: function expand_div(caller) {
                   9445:     if (top === self) {
                   9446:         document.getElementById("'.$id.'").style.width = "auto";
                   9447:         document.getElementById("'.$id.'").style.height = "auto";
                   9448:     } else {
                   9449:         try {
                   9450:             if (parent.frames) {
                   9451:                 if (parent.frames.length > 1) {
                   9452:                     var framesrc = parent.frames[1].location.href;
                   9453:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9454:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9455:                         document.getElementById("'.$id.'").style.width = "auto";
                   9456:                         document.getElementById("'.$id.'").style.height = "auto";
                   9457:                     }
                   9458:                 }
                   9459:             }
                   9460:         } catch (e) {
                   9461:             return;
                   9462:         }
1.1137    raeburn  9463:     }
1.1140    raeburn  9464:     return;
1.996     www      9465: }
1.1140    raeburn  9466: ';
                   9467:     }
                   9468:     if ($needjsready) {
                   9469:         $nicescroll_js = '
                   9470: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9471:     } else {
                   9472:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9473:     }
                   9474:     return $nicescroll_js;
1.996     www      9475: }
                   9476: 
1.318     albertel 9477: sub simple_error_page {
1.1150    bisitz   9478:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9479:     my %displayargs;
1.1151    raeburn  9480:     if (ref($args) eq 'HASH') {
                   9481:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9482:         if ($args->{'only_body'}) {
                   9483:             $displayargs{'only_body'} = 1;
                   9484:         }
                   9485:         if ($args->{'no_nav_bar'}) {
                   9486:             $displayargs{'no_nav_bar'} = 1;
                   9487:         }
1.1151    raeburn  9488:     } else {
                   9489:         $msg = &mt($msg);
                   9490:     }
1.1150    bisitz   9491: 
1.318     albertel 9492:     my $page =
1.1304    raeburn  9493: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9494: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9495: 	&Apache::loncommon::end_page();
                   9496:     if (ref($r)) {
                   9497: 	$r->print($page);
1.327     albertel 9498: 	return;
1.318     albertel 9499:     }
                   9500:     return $page;
                   9501: }
1.347     albertel 9502: 
                   9503: {
1.610     albertel 9504:     my @row_count;
1.961     onken    9505: 
                   9506:     sub start_data_table_count {
                   9507:         unshift(@row_count, 0);
                   9508:         return;
                   9509:     }
                   9510: 
                   9511:     sub end_data_table_count {
                   9512:         shift(@row_count);
                   9513:         return;
                   9514:     }
                   9515: 
1.347     albertel 9516:     sub start_data_table {
1.1018    raeburn  9517: 	my ($add_class,$id) = @_;
1.422     albertel 9518: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9519:         my $table_id;
                   9520:         if (defined($id)) {
                   9521:             $table_id = ' id="'.$id.'"';
                   9522:         }
1.961     onken    9523: 	&start_data_table_count();
1.1018    raeburn  9524: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9525:     }
                   9526: 
                   9527:     sub end_data_table {
1.961     onken    9528: 	&end_data_table_count();
1.389     albertel 9529: 	return '</table>'."\n";;
1.347     albertel 9530:     }
                   9531: 
                   9532:     sub start_data_table_row {
1.974     wenzelju 9533: 	my ($add_class, $id) = @_;
1.610     albertel 9534: 	$row_count[0]++;
                   9535: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9536: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9537:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9538:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9539:     }
1.471     banghart 9540:     
                   9541:     sub continue_data_table_row {
1.974     wenzelju 9542: 	my ($add_class, $id) = @_;
1.610     albertel 9543: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9544: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9545:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9546:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9547:     }
1.347     albertel 9548: 
                   9549:     sub end_data_table_row {
1.389     albertel 9550: 	return '</tr>'."\n";;
1.347     albertel 9551:     }
1.367     www      9552: 
1.421     albertel 9553:     sub start_data_table_empty_row {
1.707     bisitz   9554: #	$row_count[0]++;
1.421     albertel 9555: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9556:     }
                   9557: 
                   9558:     sub end_data_table_empty_row {
                   9559: 	return '</tr>'."\n";;
                   9560:     }
                   9561: 
1.367     www      9562:     sub start_data_table_header_row {
1.389     albertel 9563: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9564:     }
                   9565: 
                   9566:     sub end_data_table_header_row {
1.389     albertel 9567: 	return '</tr>'."\n";;
1.367     www      9568:     }
1.890     droeschl 9569: 
                   9570:     sub data_table_caption {
                   9571:         my $caption = shift;
                   9572:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9573:     }
1.347     albertel 9574: }
                   9575: 
1.548     albertel 9576: =pod
                   9577: 
                   9578: =item * &inhibit_menu_check($arg)
                   9579: 
                   9580: Checks for a inhibitmenu state and generates output to preserve it
                   9581: 
                   9582: Inputs:         $arg - can be any of
                   9583:                      - undef - in which case the return value is a string 
                   9584:                                to add  into arguments list of a uri
                   9585:                      - 'input' - in which case the return value is a HTML
                   9586:                                  <form> <input> field of type hidden to
                   9587:                                  preserve the value
                   9588:                      - a url - in which case the return value is the url with
                   9589:                                the neccesary cgi args added to preserve the
                   9590:                                inhibitmenu state
                   9591:                      - a ref to a url - no return value, but the string is
                   9592:                                         updated to include the neccessary cgi
                   9593:                                         args to preserve the inhibitmenu state
                   9594: 
                   9595: =cut
                   9596: 
                   9597: sub inhibit_menu_check {
                   9598:     my ($arg) = @_;
                   9599:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9600:     if ($arg eq 'input') {
                   9601: 	if ($env{'form.inhibitmenu'}) {
                   9602: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9603: 	} else {
                   9604: 	    return
                   9605: 	}
                   9606:     }
                   9607:     if ($env{'form.inhibitmenu'}) {
                   9608: 	if (ref($arg)) {
                   9609: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9610: 	} elsif ($arg eq '') {
                   9611: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9612: 	} else {
                   9613: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9614: 	}
                   9615:     }
                   9616:     if (!ref($arg)) {
                   9617: 	return $arg;
                   9618:     }
                   9619: }
                   9620: 
1.251     albertel 9621: ###############################################
1.182     matthew  9622: 
                   9623: =pod
                   9624: 
1.549     albertel 9625: =back
                   9626: 
                   9627: =head1 User Information Routines
                   9628: 
                   9629: =over 4
                   9630: 
1.405     albertel 9631: =item * &get_users_function()
1.182     matthew  9632: 
                   9633: Used by &bodytag to determine the current users primary role.
                   9634: Returns either 'student','coordinator','admin', or 'author'.
                   9635: 
                   9636: =cut
                   9637: 
                   9638: ###############################################
                   9639: sub get_users_function {
1.815     tempelho 9640:     my $function = 'norole';
1.818     tempelho 9641:     if ($env{'request.role'}=~/^(st)/) {
                   9642:         $function='student';
                   9643:     }
1.907     raeburn  9644:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9645:         $function='coordinator';
                   9646:     }
1.258     albertel 9647:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9648:         $function='admin';
                   9649:     }
1.826     bisitz   9650:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9651:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9652:         $function='author';
                   9653:     }
                   9654:     return $function;
1.54      www      9655: }
1.99      www      9656: 
                   9657: ###############################################
                   9658: 
1.233     raeburn  9659: =pod
                   9660: 
1.821     raeburn  9661: =item * &show_course()
                   9662: 
                   9663: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9664: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9665: 
                   9666: Inputs:
                   9667: None
                   9668: 
                   9669: Outputs:
                   9670: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9671: 
                   9672: =cut
                   9673: 
                   9674: ###############################################
                   9675: sub show_course {
                   9676:     my $course = !$env{'user.adv'};
                   9677:     if (!$env{'user.adv'}) {
                   9678:         foreach my $env (keys(%env)) {
                   9679:             next if ($env !~ m/^user\.priv\./);
                   9680:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9681:                 $course = 0;
                   9682:                 last;
                   9683:             }
                   9684:         }
                   9685:     }
                   9686:     return $course;
                   9687: }
                   9688: 
                   9689: ###############################################
                   9690: 
                   9691: =pod
                   9692: 
1.542     raeburn  9693: =item * &check_user_status()
1.274     raeburn  9694: 
                   9695: Determines current status of supplied role for a
                   9696: specific user. Roles can be active, previous or future.
                   9697: 
                   9698: Inputs: 
                   9699: user's domain, user's username, course's domain,
1.375     raeburn  9700: course's number, optional section ID.
1.274     raeburn  9701: 
                   9702: Outputs:
                   9703: role status: active, previous or future. 
                   9704: 
                   9705: =cut
                   9706: 
                   9707: sub check_user_status {
1.412     raeburn  9708:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9709:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9710:     my @uroles = keys(%userinfo);
1.274     raeburn  9711:     my $srchstr;
                   9712:     my $active_chk = 'none';
1.412     raeburn  9713:     my $now = time;
1.274     raeburn  9714:     if (@uroles > 0) {
1.908     raeburn  9715:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9716:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9717:         } else {
1.412     raeburn  9718:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9719:         }
                   9720:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9721:             my $role_end = 0;
                   9722:             my $role_start = 0;
                   9723:             $active_chk = 'active';
1.412     raeburn  9724:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9725:                 $role_end = $1;
                   9726:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9727:                     $role_start = $1;
1.274     raeburn  9728:                 }
                   9729:             }
                   9730:             if ($role_start > 0) {
1.412     raeburn  9731:                 if ($now < $role_start) {
1.274     raeburn  9732:                     $active_chk = 'future';
                   9733:                 }
                   9734:             }
                   9735:             if ($role_end > 0) {
1.412     raeburn  9736:                 if ($now > $role_end) {
1.274     raeburn  9737:                     $active_chk = 'previous';
                   9738:                 }
                   9739:             }
                   9740:         }
                   9741:     }
                   9742:     return $active_chk;
                   9743: }
                   9744: 
                   9745: ###############################################
                   9746: 
                   9747: =pod
                   9748: 
1.405     albertel 9749: =item * &get_sections()
1.233     raeburn  9750: 
                   9751: Determines all the sections for a course including
                   9752: sections with students and sections containing other roles.
1.419     raeburn  9753: Incoming parameters: 
                   9754: 
                   9755: 1. domain
                   9756: 2. course number 
                   9757: 3. reference to array containing roles for which sections should 
                   9758: be gathered (optional).
                   9759: 4. reference to array containing status types for which sections 
                   9760: should be gathered (optional).
                   9761: 
                   9762: If the third argument is undefined, sections are gathered for any role. 
                   9763: If the fourth argument is undefined, sections are gathered for any status.
                   9764: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9765:  
1.374     raeburn  9766: Returns section hash (keys are section IDs, values are
                   9767: number of users in each section), subject to the
1.419     raeburn  9768: optional roles filter, optional status filter 
1.233     raeburn  9769: 
                   9770: =cut
                   9771: 
                   9772: ###############################################
                   9773: sub get_sections {
1.419     raeburn  9774:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9775:     if (!defined($cdom) || !defined($cnum)) {
                   9776:         my $cid =  $env{'request.course.id'};
                   9777: 
                   9778: 	return if (!defined($cid));
                   9779: 
                   9780:         $cdom = $env{'course.'.$cid.'.domain'};
                   9781:         $cnum = $env{'course.'.$cid.'.num'};
                   9782:     }
                   9783: 
                   9784:     my %sectioncount;
1.419     raeburn  9785:     my $now = time;
1.240     albertel 9786: 
1.1118    raeburn  9787:     my $check_students = 1;
                   9788:     my $only_students = 0;
                   9789:     if (ref($possible_roles) eq 'ARRAY') {
                   9790:         if (grep(/^st$/,@{$possible_roles})) {
                   9791:             if (@{$possible_roles} == 1) {
                   9792:                 $only_students = 1;
                   9793:             }
                   9794:         } else {
                   9795:             $check_students = 0;
                   9796:         }
                   9797:     }
                   9798: 
                   9799:     if ($check_students) { 
1.276     albertel 9800: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9801: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9802: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9803:         my $start_index = &Apache::loncoursedata::CL_START();
                   9804:         my $end_index = &Apache::loncoursedata::CL_END();
                   9805:         my $status;
1.366     albertel 9806: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9807: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9808: 				                     $data->[$status_index],
                   9809:                                                      $data->[$start_index],
                   9810:                                                      $data->[$end_index]);
                   9811:             if ($stu_status eq 'Active') {
                   9812:                 $status = 'active';
                   9813:             } elsif ($end < $now) {
                   9814:                 $status = 'previous';
                   9815:             } elsif ($start > $now) {
                   9816:                 $status = 'future';
                   9817:             } 
                   9818: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9819:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9820:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9821: 		    $sectioncount{$section}++;
                   9822:                 }
1.240     albertel 9823: 	    }
                   9824: 	}
                   9825:     }
1.1118    raeburn  9826:     if ($only_students) {
                   9827:         return %sectioncount;
                   9828:     }
1.240     albertel 9829:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9830:     foreach my $user (sort(keys(%courseroles))) {
                   9831: 	if ($user !~ /^(\w{2})/) { next; }
                   9832: 	my ($role) = ($user =~ /^(\w{2})/);
                   9833: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9834: 	my ($section,$status);
1.240     albertel 9835: 	if ($role eq 'cr' &&
                   9836: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9837: 	    $section=$1;
                   9838: 	}
                   9839: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9840: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9841:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9842:         if ($end == -1 && $start == -1) {
                   9843:             next; #deleted role
                   9844:         }
                   9845:         if (!defined($possible_status)) { 
                   9846:             $sectioncount{$section}++;
                   9847:         } else {
                   9848:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9849:                 $status = 'active';
                   9850:             } elsif ($end < $now) {
                   9851:                 $status = 'future';
                   9852:             } elsif ($start > $now) {
                   9853:                 $status = 'previous';
                   9854:             }
                   9855:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9856:                 $sectioncount{$section}++;
                   9857:             }
                   9858:         }
1.233     raeburn  9859:     }
1.366     albertel 9860:     return %sectioncount;
1.233     raeburn  9861: }
                   9862: 
1.274     raeburn  9863: ###############################################
1.294     raeburn  9864: 
                   9865: =pod
1.405     albertel 9866: 
                   9867: =item * &get_course_users()
                   9868: 
1.275     raeburn  9869: Retrieves usernames:domains for users in the specified course
                   9870: with specific role(s), and access status. 
                   9871: 
                   9872: Incoming parameters:
1.277     albertel 9873: 1. course domain
                   9874: 2. course number
                   9875: 3. access status: users must have - either active, 
1.275     raeburn  9876: previous, future, or all.
1.277     albertel 9877: 4. reference to array of permissible roles
1.288     raeburn  9878: 5. reference to array of section restrictions (optional)
                   9879: 6. reference to results object (hash of hashes).
                   9880: 7. reference to optional userdata hash
1.609     raeburn  9881: 8. reference to optional statushash
1.630     raeburn  9882: 9. flag if privileged users (except those set to unhide in
                   9883:    course settings) should be excluded    
1.609     raeburn  9884: Keys of top level results hash are roles.
1.275     raeburn  9885: Keys of inner hashes are username:domain, with 
                   9886: values set to access type.
1.288     raeburn  9887: Optional userdata hash returns an array with arguments in the 
                   9888: same order as loncoursedata::get_classlist() for student data.
                   9889: 
1.609     raeburn  9890: Optional statushash returns
                   9891: 
1.288     raeburn  9892: Entries for end, start, section and status are blank because
                   9893: of the possibility of multiple values for non-student roles.
                   9894: 
1.275     raeburn  9895: =cut
1.405     albertel 9896: 
1.275     raeburn  9897: ###############################################
1.405     albertel 9898: 
1.275     raeburn  9899: sub get_course_users {
1.630     raeburn  9900:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9901:     my %idx = ();
1.419     raeburn  9902:     my %seclists;
1.288     raeburn  9903: 
                   9904:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9905:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9906:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9907:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9908:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9909:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9910:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9911:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9912: 
1.290     albertel 9913:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9914:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9915:         my $now = time;
1.277     albertel 9916:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9917:             my $match = 0;
1.412     raeburn  9918:             my $secmatch = 0;
1.419     raeburn  9919:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9920:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9921:             if ($section eq '') {
                   9922:                 $section = 'none';
                   9923:             }
1.291     albertel 9924:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9925:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9926:                     $secmatch = 1;
                   9927:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9928:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9929:                         $secmatch = 1;
                   9930:                     }
                   9931:                 } else {  
1.419     raeburn  9932: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9933: 		        $secmatch = 1;
                   9934:                     }
1.290     albertel 9935: 		}
1.412     raeburn  9936:                 if (!$secmatch) {
                   9937:                     next;
                   9938:                 }
1.419     raeburn  9939:             }
1.275     raeburn  9940:             if (defined($$types{'active'})) {
1.288     raeburn  9941:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9942:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9943:                     $match = 1;
1.275     raeburn  9944:                 }
                   9945:             }
                   9946:             if (defined($$types{'previous'})) {
1.609     raeburn  9947:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9948:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9949:                     $match = 1;
1.275     raeburn  9950:                 }
                   9951:             }
                   9952:             if (defined($$types{'future'})) {
1.609     raeburn  9953:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9954:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9955:                     $match = 1;
1.275     raeburn  9956:                 }
                   9957:             }
1.609     raeburn  9958:             if ($match) {
                   9959:                 push(@{$seclists{$student}},$section);
                   9960:                 if (ref($userdata) eq 'HASH') {
                   9961:                     $$userdata{$student} = $$classlist{$student};
                   9962:                 }
                   9963:                 if (ref($statushash) eq 'HASH') {
                   9964:                     $statushash->{$student}{'st'}{$section} = $status;
                   9965:                 }
1.288     raeburn  9966:             }
1.275     raeburn  9967:         }
                   9968:     }
1.412     raeburn  9969:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9970:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9971:         my $now = time;
1.609     raeburn  9972:         my %displaystatus = ( previous => 'Expired',
                   9973:                               active   => 'Active',
                   9974:                               future   => 'Future',
                   9975:                             );
1.1121    raeburn  9976:         my (%nothide,@possdoms);
1.630     raeburn  9977:         if ($hidepriv) {
                   9978:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9979:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9980:                 if ($user !~ /:/) {
                   9981:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9982:                 } else {
                   9983:                     $nothide{$user} = 1;
                   9984:                 }
                   9985:             }
1.1121    raeburn  9986:             my @possdoms = ($cdom);
                   9987:             if ($coursehash{'checkforpriv'}) {
                   9988:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9989:             }
1.630     raeburn  9990:         }
1.439     raeburn  9991:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9992:             my $match = 0;
1.412     raeburn  9993:             my $secmatch = 0;
1.439     raeburn  9994:             my $status;
1.412     raeburn  9995:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9996:             $user =~ s/:$//;
1.439     raeburn  9997:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9998:             if ($end == -1 || $start == -1) {
                   9999:                 next;
                   10000:             }
                   10001:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10002:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10003:                 my ($uname,$udom) = split(/:/,$user);
                   10004:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10005:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10006:                         $secmatch = 1;
                   10007:                     } elsif ($usec eq '') {
1.420     albertel 10008:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10009:                             $secmatch = 1;
                   10010:                         }
                   10011:                     } else {
                   10012:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10013:                             $secmatch = 1;
                   10014:                         }
                   10015:                     }
                   10016:                     if (!$secmatch) {
                   10017:                         next;
                   10018:                     }
1.288     raeburn  10019:                 }
1.419     raeburn  10020:                 if ($usec eq '') {
                   10021:                     $usec = 'none';
                   10022:                 }
1.275     raeburn  10023:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10024:                     if ($hidepriv) {
1.1121    raeburn  10025:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10026:                             (!$nothide{$uname.':'.$udom})) {
                   10027:                             next;
                   10028:                         }
                   10029:                     }
1.503     raeburn  10030:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10031:                         $status = 'previous';
                   10032:                     } elsif ($start > $now) {
                   10033:                         $status = 'future';
                   10034:                     } else {
                   10035:                         $status = 'active';
                   10036:                     }
1.277     albertel 10037:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10038:                         if ($status eq $type) {
1.420     albertel 10039:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10040:                                 push(@{$$users{$role}{$user}},$type);
                   10041:                             }
1.288     raeburn  10042:                             $match = 1;
                   10043:                         }
                   10044:                     }
1.419     raeburn  10045:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10046:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10047: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10048:                         }
1.420     albertel 10049:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10050:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10051:                         }
1.609     raeburn  10052:                         if (ref($statushash) eq 'HASH') {
                   10053:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10054:                         }
1.275     raeburn  10055:                     }
                   10056:                 }
                   10057:             }
                   10058:         }
1.290     albertel 10059:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10060:             if ((defined($cdom)) && (defined($cnum))) {
                   10061:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10062:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10063:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10064:                     next if ($owner eq '');
                   10065:                     my ($ownername,$ownerdom);
                   10066:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10067:                         $ownername = $1;
                   10068:                         $ownerdom = $2;
                   10069:                     } else {
                   10070:                         $ownername = $owner;
                   10071:                         $ownerdom = $cdom;
                   10072:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10073:                     }
                   10074:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10075:                     if (defined($userdata) && 
1.609     raeburn  10076: 			!exists($$userdata{$owner})) {
                   10077: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10078:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10079:                             push(@{$seclists{$owner}},'none');
                   10080:                         }
                   10081:                         if (ref($statushash) eq 'HASH') {
                   10082:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10083:                         }
1.290     albertel 10084: 		    }
1.279     raeburn  10085:                 }
                   10086:             }
                   10087:         }
1.419     raeburn  10088:         foreach my $user (keys(%seclists)) {
                   10089:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10090:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10091:         }
1.275     raeburn  10092:     }
                   10093:     return;
                   10094: }
                   10095: 
1.288     raeburn  10096: sub get_user_info {
                   10097:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10098:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10099: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10100:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10101:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10102:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10103:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10104:     return;
                   10105: }
1.275     raeburn  10106: 
1.472     raeburn  10107: ###############################################
                   10108: 
                   10109: =pod
                   10110: 
                   10111: =item * &get_user_quota()
                   10112: 
1.1134    raeburn  10113: Retrieves quota assigned for storage of user files.
                   10114: Default is to report quota for portfolio files.
1.472     raeburn  10115: 
                   10116: Incoming parameters:
                   10117: 1. user's username
                   10118: 2. user's domain
1.1134    raeburn  10119: 3. quota name - portfolio, author, or course
1.1136    raeburn  10120:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10121: 4. crstype - official, unofficial, textbook, placement or community, 
                   10122:    if quota name is course
1.472     raeburn  10123: 
                   10124: Returns:
1.1163    raeburn  10125: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10126: 2. (Optional) Type of setting: custom or default
                   10127:    (individually assigned or default for user's 
                   10128:    institutional status).
                   10129: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10130:    or student - types as defined in localenroll::inst_usertypes 
                   10131:    for user's domain, which determines default quota for user.
                   10132: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10133: 
                   10134: If a value has been stored in the user's environment, 
1.536     raeburn  10135: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10136: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10137: 
                   10138: =cut
                   10139: 
                   10140: ###############################################
                   10141: 
                   10142: 
                   10143: sub get_user_quota {
1.1136    raeburn  10144:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10145:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10146:     if (!defined($udom)) {
                   10147:         $udom = $env{'user.domain'};
                   10148:     }
                   10149:     if (!defined($uname)) {
                   10150:         $uname = $env{'user.name'};
                   10151:     }
                   10152:     if (($udom eq '' || $uname eq '') ||
                   10153:         ($udom eq 'public') && ($uname eq 'public')) {
                   10154:         $quota = 0;
1.536     raeburn  10155:         $quotatype = 'default';
                   10156:         $defquota = 0; 
1.472     raeburn  10157:     } else {
1.536     raeburn  10158:         my $inststatus;
1.1134    raeburn  10159:         if ($quotaname eq 'course') {
                   10160:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10161:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10162:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10163:             } else {
                   10164:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10165:                 $quota = $cenv{'internal.uploadquota'};
                   10166:             }
1.536     raeburn  10167:         } else {
1.1134    raeburn  10168:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10169:                 if ($quotaname eq 'author') {
                   10170:                     $quota = $env{'environment.authorquota'};
                   10171:                 } else {
                   10172:                     $quota = $env{'environment.portfolioquota'};
                   10173:                 }
                   10174:                 $inststatus = $env{'environment.inststatus'};
                   10175:             } else {
                   10176:                 my %userenv = 
                   10177:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10178:                                          'authorquota','inststatus'],$udom,$uname);
                   10179:                 my ($tmp) = keys(%userenv);
                   10180:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10181:                     if ($quotaname eq 'author') {
                   10182:                         $quota = $userenv{'authorquota'};
                   10183:                     } else {
                   10184:                         $quota = $userenv{'portfolioquota'};
                   10185:                     }
                   10186:                     $inststatus = $userenv{'inststatus'};
                   10187:                 } else {
                   10188:                     undef(%userenv);
                   10189:                 }
                   10190:             }
                   10191:         }
                   10192:         if ($quota eq '' || wantarray) {
                   10193:             if ($quotaname eq 'course') {
                   10194:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10195:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10196:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10197:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10198:                     $defquota = $domdefs{$crstype.'quota'};
                   10199:                 }
                   10200:                 if ($defquota eq '') {
                   10201:                     $defquota = 500;
                   10202:                 }
1.1134    raeburn  10203:             } else {
                   10204:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10205:             }
                   10206:             if ($quota eq '') {
                   10207:                 $quota = $defquota;
                   10208:                 $quotatype = 'default';
                   10209:             } else {
                   10210:                 $quotatype = 'custom';
                   10211:             }
1.472     raeburn  10212:         }
                   10213:     }
1.536     raeburn  10214:     if (wantarray) {
                   10215:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10216:     } else {
                   10217:         return $quota;
                   10218:     }
1.472     raeburn  10219: }
                   10220: 
                   10221: ###############################################
                   10222: 
                   10223: =pod
                   10224: 
                   10225: =item * &default_quota()
                   10226: 
1.536     raeburn  10227: Retrieves default quota assigned for storage of user portfolio files,
                   10228: given an (optional) user's institutional status.
1.472     raeburn  10229: 
                   10230: Incoming parameters:
1.1142    raeburn  10231: 
1.472     raeburn  10232: 1. domain
1.536     raeburn  10233: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10234:    status types (e.g., faculty, staff, student etc.)
                   10235:    which apply to the user for whom the default is being retrieved.
                   10236:    If the institutional status string in undefined, the domain
1.1134    raeburn  10237:    default quota will be returned.
                   10238: 3.  quota name - portfolio, author, or course
                   10239:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10240: 
                   10241: Returns:
1.1142    raeburn  10242: 
1.1163    raeburn  10243: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10244: 2. (Optional) institutional type which determined the value of the
                   10245:    default quota.
1.472     raeburn  10246: 
                   10247: If a value has been stored in the domain's configuration db,
                   10248: it will return that, otherwise it returns 20 (for backwards 
                   10249: compatibility with domains which have not set up a configuration
1.1163    raeburn  10250: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10251: 
1.536     raeburn  10252: If the user's status includes multiple types (e.g., staff and student),
                   10253: the largest default quota which applies to the user determines the
                   10254: default quota returned.
                   10255: 
1.472     raeburn  10256: =cut
                   10257: 
                   10258: ###############################################
                   10259: 
                   10260: 
                   10261: sub default_quota {
1.1134    raeburn  10262:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10263:     my ($defquota,$settingstatus);
                   10264:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10265:                                             ['quotas'],$udom);
1.1134    raeburn  10266:     my $key = 'defaultquota';
                   10267:     if ($quotaname eq 'author') {
                   10268:         $key = 'authorquota';
                   10269:     }
1.622     raeburn  10270:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10271:         if ($inststatus ne '') {
1.765     raeburn  10272:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10273:             foreach my $item (@statuses) {
1.1134    raeburn  10274:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10275:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10276:                         if ($defquota eq '') {
1.1134    raeburn  10277:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10278:                             $settingstatus = $item;
1.1134    raeburn  10279:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10280:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10281:                             $settingstatus = $item;
                   10282:                         }
                   10283:                     }
1.1134    raeburn  10284:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10285:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10286:                         if ($defquota eq '') {
                   10287:                             $defquota = $quotahash{'quotas'}{$item};
                   10288:                             $settingstatus = $item;
                   10289:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10290:                             $defquota = $quotahash{'quotas'}{$item};
                   10291:                             $settingstatus = $item;
                   10292:                         }
1.536     raeburn  10293:                     }
                   10294:                 }
                   10295:             }
                   10296:         }
                   10297:         if ($defquota eq '') {
1.1134    raeburn  10298:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10299:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10300:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10301:                 $defquota = $quotahash{'quotas'}{'default'};
                   10302:             }
1.536     raeburn  10303:             $settingstatus = 'default';
1.1139    raeburn  10304:             if ($defquota eq '') {
                   10305:                 if ($quotaname eq 'author') {
                   10306:                     $defquota = 500;
                   10307:                 }
                   10308:             }
1.536     raeburn  10309:         }
                   10310:     } else {
                   10311:         $settingstatus = 'default';
1.1134    raeburn  10312:         if ($quotaname eq 'author') {
                   10313:             $defquota = 500;
                   10314:         } else {
                   10315:             $defquota = 20;
                   10316:         }
1.536     raeburn  10317:     }
                   10318:     if (wantarray) {
                   10319:         return ($defquota,$settingstatus);
1.472     raeburn  10320:     } else {
1.536     raeburn  10321:         return $defquota;
1.472     raeburn  10322:     }
                   10323: }
                   10324: 
1.1135    raeburn  10325: ###############################################
                   10326: 
                   10327: =pod
                   10328: 
1.1136    raeburn  10329: =item * &excess_filesize_warning()
1.1135    raeburn  10330: 
                   10331: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10332: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10333: space to be exceeded.
1.1136    raeburn  10334: 
                   10335: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10336: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10337: 
1.1165    raeburn  10338: Inputs: 7 
1.1136    raeburn  10339: 1. username or coursenum
1.1135    raeburn  10340: 2. domain
1.1136    raeburn  10341: 3. context ('author' or 'course')
1.1135    raeburn  10342: 4. filename of file for which action is being requested
                   10343: 5. filesize (kB) of file
                   10344: 6. action being taken: copy or upload.
1.1237    raeburn  10345: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10346: 
                   10347: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10348:          otherwise return null.
                   10349: 
                   10350: =back
1.1135    raeburn  10351: 
                   10352: =cut
                   10353: 
1.1136    raeburn  10354: sub excess_filesize_warning {
1.1165    raeburn  10355:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10356:     my $current_disk_usage = 0;
1.1165    raeburn  10357:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10358:     if ($context eq 'author') {
                   10359:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10360:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10361:     } else {
                   10362:         foreach my $subdir ('docs','supplemental') {
                   10363:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10364:         }
                   10365:     }
1.1135    raeburn  10366:     $disk_quota = int($disk_quota * 1000);
                   10367:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10368:         return '<p class="LC_warning">'.
1.1135    raeburn  10369:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10370:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10371:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10372:                             $disk_quota,$current_disk_usage).
                   10373:                '</p>';
                   10374:     }
                   10375:     return;
                   10376: }
                   10377: 
                   10378: ###############################################
                   10379: 
                   10380: 
1.1136    raeburn  10381: 
                   10382: 
1.384     raeburn  10383: sub get_secgrprole_info {
                   10384:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10385:     my %sections_count = &get_sections($cdom,$cnum);
                   10386:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10387:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10388:     my @groups = sort(keys(%curr_groups));
                   10389:     my $allroles = [];
                   10390:     my $rolehash;
                   10391:     my $accesshash = {
                   10392:                      active => 'Currently has access',
                   10393:                      future => 'Will have future access',
                   10394:                      previous => 'Previously had access',
                   10395:                   };
                   10396:     if ($needroles) {
                   10397:         $rolehash = {'all' => 'all'};
1.385     albertel 10398:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10399: 	if (&Apache::lonnet::error(%user_roles)) {
                   10400: 	    undef(%user_roles);
                   10401: 	}
                   10402:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10403:             my ($role)=split(/\:/,$item,2);
                   10404:             if ($role eq 'cr') { next; }
                   10405:             if ($role =~ /^cr/) {
                   10406:                 $$rolehash{$role} = (split('/',$role))[3];
                   10407:             } else {
                   10408:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10409:             }
                   10410:         }
                   10411:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10412:             push(@{$allroles},$key);
                   10413:         }
                   10414:         push (@{$allroles},'st');
                   10415:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10416:     }
                   10417:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10418: }
                   10419: 
1.555     raeburn  10420: sub user_picker {
1.1279    raeburn  10421:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10422:     my $currdom = $dom;
1.1253    raeburn  10423:     my @alldoms = &Apache::lonnet::all_domains();
                   10424:     if (@alldoms == 1) {
                   10425:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10426:                                                ['directorysrch'],$alldoms[0]);
                   10427:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10428:         my $showdom = $domdesc;
                   10429:         if ($showdom eq '') {
                   10430:             $showdom = $dom;
                   10431:         }
                   10432:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10433:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10434:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10435:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10436:             }
                   10437:         }
                   10438:     }
1.555     raeburn  10439:     my %curr_selected = (
                   10440:                         srchin => 'dom',
1.580     raeburn  10441:                         srchby => 'lastname',
1.555     raeburn  10442:                       );
                   10443:     my $srchterm;
1.625     raeburn  10444:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10445:         if ($srch->{'srchby'} ne '') {
                   10446:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10447:         }
                   10448:         if ($srch->{'srchin'} ne '') {
                   10449:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10450:         }
                   10451:         if ($srch->{'srchtype'} ne '') {
                   10452:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10453:         }
                   10454:         if ($srch->{'srchdomain'} ne '') {
                   10455:             $currdom = $srch->{'srchdomain'};
                   10456:         }
                   10457:         $srchterm = $srch->{'srchterm'};
                   10458:     }
1.1222    damieng  10459:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10460:                     'usr'       => 'Search criteria',
1.563     raeburn  10461:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10462:                     'uname'     => 'username',
                   10463:                     'lastname'  => 'last name',
1.555     raeburn  10464:                     'lastfirst' => 'last name, first name',
1.558     albertel 10465:                     'crs'       => 'in this course',
1.576     raeburn  10466:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10467:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10468:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10469:                     'exact'     => 'is',
                   10470:                     'contains'  => 'contains',
1.569     raeburn  10471:                     'begins'    => 'begins with',
1.1222    damieng  10472:                                        );
                   10473:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10474:                     'youm'      => "You must include some text to search for.",
                   10475:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10476:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10477:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10478:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10479:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10480:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10481:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10482:                                        );
1.1222    damieng  10483:     &html_escape(\%html_lt);
                   10484:     &js_escape(\%js_lt);
1.1255    raeburn  10485:     my $domform;
1.1277    raeburn  10486:     my $allow_blank = 1;
1.1255    raeburn  10487:     if ($fixeddom) {
1.1277    raeburn  10488:         $allow_blank = 0;
                   10489:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10490:     } else {
1.1287    raeburn  10491:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10492:         my ($trusted,$untrusted);
1.1287    raeburn  10493:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10494:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10495:         } elsif ($context eq 'author') {
1.1288    raeburn  10496:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10497:         } elsif ($context eq 'domain') {
1.1288    raeburn  10498:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10499:         }
1.1288    raeburn  10500:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10501:     }
1.563     raeburn  10502:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10503: 
                   10504:     my @srchins = ('crs','dom','alc','instd');
                   10505: 
                   10506:     foreach my $option (@srchins) {
                   10507:         # FIXME 'alc' option unavailable until 
                   10508:         #       loncreateuser::print_user_query_page()
                   10509:         #       has been completed.
                   10510:         next if ($option eq 'alc');
1.880     raeburn  10511:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10512:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10513:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10514:         if ($curr_selected{'srchin'} eq $option) {
                   10515:             $srchinsel .= ' 
1.1222    damieng  10516:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10517:         } else {
                   10518:             $srchinsel .= '
1.1222    damieng  10519:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10520:         }
1.555     raeburn  10521:     }
1.563     raeburn  10522:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10523: 
                   10524:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10525:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10526:         if ($curr_selected{'srchby'} eq $option) {
                   10527:             $srchbysel .= '
1.1222    damieng  10528:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10529:         } else {
                   10530:             $srchbysel .= '
1.1222    damieng  10531:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10532:          }
                   10533:     }
                   10534:     $srchbysel .= "\n  </select>\n";
                   10535: 
                   10536:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10537:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10538:         if ($curr_selected{'srchtype'} eq $option) {
                   10539:             $srchtypesel .= '
1.1222    damieng  10540:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10541:         } else {
                   10542:             $srchtypesel .= '
1.1222    damieng  10543:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10544:         }
                   10545:     }
                   10546:     $srchtypesel .= "\n  </select>\n";
                   10547: 
1.558     albertel 10548:     my ($newuserscript,$new_user_create);
1.994     raeburn  10549:     my $context_dom = $env{'request.role.domain'};
                   10550:     if ($context eq 'requestcrs') {
                   10551:         if ($env{'form.coursedom'} ne '') { 
                   10552:             $context_dom = $env{'form.coursedom'};
                   10553:         }
                   10554:     }
1.556     raeburn  10555:     if ($forcenewuser) {
1.576     raeburn  10556:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10557:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10558:                 if ($cancreate) {
                   10559:                     $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>';
                   10560:                 } else {
1.799     bisitz   10561:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10562:                     my %usertypetext = (
                   10563:                         official   => 'institutional',
                   10564:                         unofficial => 'non-institutional',
                   10565:                     );
1.799     bisitz   10566:                     $new_user_create = '<p class="LC_warning">'
                   10567:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10568:                                       .' '
                   10569:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10570:                                           ,'<a href="'.$helplink.'">','</a>')
                   10571:                                       .'</p><br />';
1.627     raeburn  10572:                 }
1.576     raeburn  10573:             }
                   10574:         }
                   10575: 
1.556     raeburn  10576:         $newuserscript = <<"ENDSCRIPT";
                   10577: 
1.570     raeburn  10578: function setSearch(createnew,callingForm) {
1.556     raeburn  10579:     if (createnew == 1) {
1.570     raeburn  10580:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10581:             if (callingForm.srchby.options[i].value == 'uname') {
                   10582:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10583:             }
                   10584:         }
1.570     raeburn  10585:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10586:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10587: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10588:             }
                   10589:         }
1.570     raeburn  10590:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10591:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10592:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10593:             }
                   10594:         }
1.570     raeburn  10595:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10596:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10597:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10598:             }
                   10599:         }
                   10600:     }
                   10601: }
                   10602: ENDSCRIPT
1.558     albertel 10603: 
1.556     raeburn  10604:     }
                   10605: 
1.555     raeburn  10606:     my $output = <<"END_BLOCK";
1.556     raeburn  10607: <script type="text/javascript">
1.824     bisitz   10608: // <![CDATA[
1.570     raeburn  10609: function validateEntry(callingForm) {
1.558     albertel 10610: 
1.556     raeburn  10611:     var checkok = 1;
1.558     albertel 10612:     var srchin;
1.570     raeburn  10613:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10614: 	if ( callingForm.srchin[i].checked ) {
                   10615: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10616: 	}
                   10617:     }
                   10618: 
1.570     raeburn  10619:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10620:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10621:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10622:     var srchterm =  callingForm.srchterm.value;
                   10623:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10624:     var msg = "";
                   10625: 
                   10626:     if (srchterm == "") {
                   10627:         checkok = 0;
1.1222    damieng  10628:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10629:     }
                   10630: 
1.569     raeburn  10631:     if (srchtype== 'begins') {
                   10632:         if (srchterm.length < 2) {
                   10633:             checkok = 0;
1.1222    damieng  10634:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10635:         }
                   10636:     }
                   10637: 
1.556     raeburn  10638:     if (srchtype== 'contains') {
                   10639:         if (srchterm.length < 3) {
                   10640:             checkok = 0;
1.1222    damieng  10641:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10642:         }
                   10643:     }
                   10644:     if (srchin == 'instd') {
                   10645:         if (srchdomain == '') {
                   10646:             checkok = 0;
1.1222    damieng  10647:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10648:         }
                   10649:     }
                   10650:     if (srchin == 'dom') {
                   10651:         if (srchdomain == '') {
                   10652:             checkok = 0;
1.1222    damieng  10653:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10654:         }
                   10655:     }
                   10656:     if (srchby == 'lastfirst') {
                   10657:         if (srchterm.indexOf(",") == -1) {
                   10658:             checkok = 0;
1.1222    damieng  10659:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10660:         }
                   10661:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10662:             checkok = 0;
1.1222    damieng  10663:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10664:         }
                   10665:     }
                   10666:     if (checkok == 0) {
1.1222    damieng  10667:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10668:         return;
                   10669:     }
                   10670:     if (checkok == 1) {
1.570     raeburn  10671:         callingForm.submit();
1.556     raeburn  10672:     }
                   10673: }
                   10674: 
                   10675: $newuserscript
                   10676: 
1.824     bisitz   10677: // ]]>
1.556     raeburn  10678: </script>
1.558     albertel 10679: 
                   10680: $new_user_create
                   10681: 
1.555     raeburn  10682: END_BLOCK
1.558     albertel 10683: 
1.876     raeburn  10684:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10685:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10686:                $domform.
                   10687:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10688:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10689:                $srchbysel.
                   10690:                $srchtypesel. 
                   10691:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10692:                $srchinsel.
                   10693:                &Apache::lonhtmlcommon::row_closure(1). 
                   10694:                &Apache::lonhtmlcommon::end_pick_box().
                   10695:                '<br />';
1.1253    raeburn  10696:     return ($output,1);
1.555     raeburn  10697: }
                   10698: 
1.612     raeburn  10699: sub user_rule_check {
1.615     raeburn  10700:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10701:     my ($response,%inst_response);
1.612     raeburn  10702:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10703:         if (keys(%{$usershash}) > 1) {
                   10704:             my (%by_username,%by_id,%userdoms);
                   10705:             my $checkid; 
                   10706:             if (ref($checks) eq 'HASH') {
                   10707:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10708:                     $checkid = 1;
                   10709:                 }
                   10710:             }
                   10711:             foreach my $user (keys(%{$usershash})) {
                   10712:                 my ($uname,$udom) = split(/:/,$user);
                   10713:                 if ($checkid) {
                   10714:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10715:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10716:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10717:                             $userdoms{$udom} = 1;
1.1227    raeburn  10718:                             if (ref($inst_results) eq 'HASH') {
                   10719:                                 $inst_results->{$uname.':'.$udom} = {};
                   10720:                             }
1.1226    raeburn  10721:                         }
                   10722:                     }
                   10723:                 } else {
                   10724:                     $by_username{$udom}{$uname} = 1;
                   10725:                     $userdoms{$udom} = 1;
1.1227    raeburn  10726:                     if (ref($inst_results) eq 'HASH') {
                   10727:                         $inst_results->{$uname.':'.$udom} = {};
                   10728:                     }
1.1226    raeburn  10729:                 }
                   10730:             }
                   10731:             foreach my $udom (keys(%userdoms)) {
                   10732:                 if (!$got_rules->{$udom}) {
                   10733:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10734:                                                              ['usercreation'],$udom);
                   10735:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10736:                         foreach my $item ('username','id') {
                   10737:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10738:                                 $$curr_rules{$udom}{$item} =
                   10739:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10740:                             }
                   10741:                         }
                   10742:                     }
                   10743:                     $got_rules->{$udom} = 1;
                   10744:                 }
1.612     raeburn  10745:             }
1.1226    raeburn  10746:             if ($checkid) {
                   10747:                 foreach my $udom (keys(%by_id)) {
                   10748:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10749:                     if ($outcome eq 'ok') {
1.1227    raeburn  10750:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10751:                             my $uname = $by_id{$udom}{$id};
                   10752:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10753:                         }
1.1226    raeburn  10754:                         if (ref($results) eq 'HASH') {
                   10755:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10756:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10757:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10758:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10759:                                 }
1.1226    raeburn  10760:                             }
                   10761:                         }
                   10762:                     }
1.612     raeburn  10763:                 }
1.615     raeburn  10764:             } else {
1.1226    raeburn  10765:                 foreach my $udom (keys(%by_username)) {
                   10766:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10767:                     if ($outcome eq 'ok') {
1.1227    raeburn  10768:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10769:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10770:                         }
1.1226    raeburn  10771:                         if (ref($results) eq 'HASH') {
                   10772:                             foreach my $uname (keys(%{$results})) {
                   10773:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10774:                             }
                   10775:                         }
                   10776:                     }
                   10777:                 }
1.612     raeburn  10778:             }
1.1226    raeburn  10779:         } elsif (keys(%{$usershash}) == 1) {
                   10780:             my $user = (keys(%{$usershash}))[0];
                   10781:             my ($uname,$udom) = split(/:/,$user);
                   10782:             if (($udom ne '') && ($uname ne '')) {
                   10783:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10784:                     if (ref($checks) eq 'HASH') {
                   10785:                         if (defined($checks->{'username'})) {
                   10786:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10787:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10788:                         } elsif (defined($checks->{'id'})) {
                   10789:                             if ($usershash->{$user}->{'id'} ne '') {
                   10790:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10791:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10792:                                                                   $usershash->{$user}->{'id'});
                   10793:                             } else {
                   10794:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10795:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10796:                             }
1.585     raeburn  10797:                         }
1.1226    raeburn  10798:                     } else {
                   10799:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10800:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10801:                        return;
                   10802:                     }
                   10803:                     if (!$got_rules->{$udom}) {
                   10804:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10805:                                                                  ['usercreation'],$udom);
                   10806:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10807:                             foreach my $item ('username','id') {
                   10808:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10809:                                    $$curr_rules{$udom}{$item} = 
                   10810:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10811:                                 }
                   10812:                             }
                   10813:                         }
                   10814:                         $got_rules->{$udom} = 1;
1.585     raeburn  10815:                     }
                   10816:                 }
1.1226    raeburn  10817:             } else {
                   10818:                 return;
                   10819:             }
                   10820:         } else {
                   10821:             return;
                   10822:         }
                   10823:         foreach my $user (keys(%{$usershash})) {
                   10824:             my ($uname,$udom) = split(/:/,$user);
                   10825:             next if (($udom eq '') || ($uname eq ''));
                   10826:             my $id;
1.1227    raeburn  10827:             if (ref($inst_results) eq 'HASH') {
                   10828:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10829:                     $id = $inst_results->{$user}->{'id'};
                   10830:                 }
                   10831:             }
                   10832:             if ($id eq '') { 
                   10833:                 if (ref($usershash->{$user})) {
                   10834:                     $id = $usershash->{$user}->{'id'};
                   10835:                 }
1.585     raeburn  10836:             }
1.612     raeburn  10837:             foreach my $item (keys(%{$checks})) {
                   10838:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10839:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10840:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10841:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10842:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10843:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10844:                                 if ($rule_check{$rule}) {
                   10845:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10846:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10847:                                         if (ref($inst_results) eq 'HASH') {
                   10848:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10849:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10850:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10851:                                                 } elsif ($item eq 'id') {
                   10852:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10853:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10854:                                                     }
1.615     raeburn  10855:                                                 }
1.612     raeburn  10856:                                             }
                   10857:                                         }
1.615     raeburn  10858:                                     }
                   10859:                                     last;
1.585     raeburn  10860:                                 }
                   10861:                             }
                   10862:                         }
                   10863:                     }
                   10864:                 }
                   10865:             }
                   10866:         }
                   10867:     }
1.612     raeburn  10868:     return;
                   10869: }
                   10870: 
                   10871: sub user_rule_formats {
                   10872:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10873:     my %text = ( 
                   10874:                  'username' => 'Usernames',
                   10875:                  'id'       => 'IDs',
                   10876:                );
                   10877:     my $output;
                   10878:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10879:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10880:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10881:             $output = '<br />'.
                   10882:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10883:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10884:                       ' <ul>';
1.612     raeburn  10885:             foreach my $rule (@{$ruleorder}) {
                   10886:                 if (ref($curr_rules) eq 'ARRAY') {
                   10887:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10888:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10889:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10890:                                         $rules->{$rule}{'desc'}.'</li>';
                   10891:                         }
                   10892:                     }
                   10893:                 }
                   10894:             }
                   10895:             $output .= '</ul>';
                   10896:         }
                   10897:     }
                   10898:     return $output;
                   10899: }
                   10900: 
                   10901: sub instrule_disallow_msg {
1.615     raeburn  10902:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10903:     my $response;
                   10904:     my %text = (
                   10905:                   item   => 'username',
                   10906:                   items  => 'usernames',
                   10907:                   match  => 'matches',
                   10908:                   do     => 'does',
                   10909:                   action => 'a username',
                   10910:                   one    => 'one',
                   10911:                );
                   10912:     if ($count > 1) {
                   10913:         $text{'item'} = 'usernames';
                   10914:         $text{'match'} ='match';
                   10915:         $text{'do'} = 'do';
                   10916:         $text{'action'} = 'usernames',
                   10917:         $text{'one'} = 'ones';
                   10918:     }
                   10919:     if ($checkitem eq 'id') {
                   10920:         $text{'items'} = 'IDs';
                   10921:         $text{'item'} = 'ID';
                   10922:         $text{'action'} = 'an ID';
1.615     raeburn  10923:         if ($count > 1) {
                   10924:             $text{'item'} = 'IDs';
                   10925:             $text{'action'} = 'IDs';
                   10926:         }
1.612     raeburn  10927:     }
1.674     bisitz   10928:     $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  10929:     if ($mode eq 'upload') {
                   10930:         if ($checkitem eq 'username') {
                   10931:             $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'}.");
                   10932:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10933:             $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  10934:         }
1.669     raeburn  10935:     } elsif ($mode eq 'selfcreate') {
                   10936:         if ($checkitem eq 'id') {
                   10937:             $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.");
                   10938:         }
1.615     raeburn  10939:     } else {
                   10940:         if ($checkitem eq 'username') {
                   10941:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10942:         } elsif ($checkitem eq 'id') {
                   10943:             $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.");
                   10944:         }
1.612     raeburn  10945:     }
                   10946:     return $response;
1.585     raeburn  10947: }
                   10948: 
1.624     raeburn  10949: sub personal_data_fieldtitles {
                   10950:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10951:                         id => 'Student/Employee ID',
                   10952:                         permanentemail => 'E-mail address',
                   10953:                         lastname => 'Last Name',
                   10954:                         firstname => 'First Name',
                   10955:                         middlename => 'Middle Name',
                   10956:                         generation => 'Generation',
                   10957:                         gen => 'Generation',
1.765     raeburn  10958:                         inststatus => 'Affiliation',
1.624     raeburn  10959:                    );
                   10960:     return %fieldtitles;
                   10961: }
                   10962: 
1.642     raeburn  10963: sub sorted_inst_types {
                   10964:     my ($dom) = @_;
1.1185    raeburn  10965:     my ($usertypes,$order);
                   10966:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10967:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10968:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10969:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10970:     } else {
                   10971:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10972:     }
1.642     raeburn  10973:     my $othertitle = &mt('All users');
                   10974:     if ($env{'request.course.id'}) {
1.668     raeburn  10975:         $othertitle  = &mt('Any users');
1.642     raeburn  10976:     }
                   10977:     my @types;
                   10978:     if (ref($order) eq 'ARRAY') {
                   10979:         @types = @{$order};
                   10980:     }
                   10981:     if (@types == 0) {
                   10982:         if (ref($usertypes) eq 'HASH') {
                   10983:             @types = sort(keys(%{$usertypes}));
                   10984:         }
                   10985:     }
                   10986:     if (keys(%{$usertypes}) > 0) {
                   10987:         $othertitle = &mt('Other users');
                   10988:     }
                   10989:     return ($othertitle,$usertypes,\@types);
                   10990: }
                   10991: 
1.645     raeburn  10992: sub get_institutional_codes {
                   10993:     my ($settings,$allcourses,$LC_code) = @_;
                   10994: # Get complete list of course sections to update
                   10995:     my @currsections = ();
                   10996:     my @currxlists = ();
                   10997:     my $coursecode = $$settings{'internal.coursecode'};
                   10998: 
                   10999:     if ($$settings{'internal.sectionnums'} ne '') {
                   11000:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11001:     }
                   11002: 
                   11003:     if ($$settings{'internal.crosslistings'} ne '') {
                   11004:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11005:     }
                   11006: 
                   11007:     if (@currxlists > 0) {
                   11008:         foreach (@currxlists) {
                   11009:             if (m/^([^:]+):(\w*)$/) {
                   11010:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11011:                     push(@{$allcourses},$1);
1.645     raeburn  11012:                     $$LC_code{$1} = $2;
                   11013:                 }
                   11014:             }
                   11015:         }
                   11016:     }
                   11017:  
                   11018:     if (@currsections > 0) {
                   11019:         foreach (@currsections) {
                   11020:             if (m/^(\w+):(\w*)$/) {
                   11021:                 my $sec = $coursecode.$1;
                   11022:                 my $lc_sec = $2;
                   11023:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  11024:                     push(@{$allcourses},$sec);
1.645     raeburn  11025:                     $$LC_code{$sec} = $lc_sec;
                   11026:                 }
                   11027:             }
                   11028:         }
                   11029:     }
                   11030:     return;
                   11031: }
                   11032: 
1.971     raeburn  11033: sub get_standard_codeitems {
                   11034:     return ('Year','Semester','Department','Number','Section');
                   11035: }
                   11036: 
1.112     bowersj2 11037: =pod
                   11038: 
1.780     raeburn  11039: =head1 Slot Helpers
                   11040: 
                   11041: =over 4
                   11042: 
                   11043: =item * sorted_slots()
                   11044: 
1.1040    raeburn  11045: Sorts an array of slot names in order of an optional sort key,
                   11046: default sort is by slot start time (earliest first). 
1.780     raeburn  11047: 
                   11048: Inputs:
                   11049: 
                   11050: =over 4
                   11051: 
                   11052: slotsarr  - Reference to array of unsorted slot names.
                   11053: 
                   11054: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11055: 
1.1040    raeburn  11056: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11057: 
1.549     albertel 11058: =back
                   11059: 
1.780     raeburn  11060: Returns:
                   11061: 
                   11062: =over 4
                   11063: 
1.1040    raeburn  11064: sorted   - An array of slot names sorted by a specified sort key 
                   11065:            (default sort key is start time of the slot).
1.780     raeburn  11066: 
                   11067: =back
                   11068: 
                   11069: =cut
                   11070: 
                   11071: 
                   11072: sub sorted_slots {
1.1040    raeburn  11073:     my ($slotsarr,$slots,$sortkey) = @_;
                   11074:     if ($sortkey eq '') {
                   11075:         $sortkey = 'starttime';
                   11076:     }
1.780     raeburn  11077:     my @sorted;
                   11078:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11079:         @sorted =
                   11080:             sort {
                   11081:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11082:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11083:                      }
                   11084:                      if (ref($slots->{$a})) { return -1;}
                   11085:                      if (ref($slots->{$b})) { return 1;}
                   11086:                      return 0;
                   11087:                  } @{$slotsarr};
                   11088:     }
                   11089:     return @sorted;
                   11090: }
                   11091: 
1.1040    raeburn  11092: =pod
                   11093: 
                   11094: =item * get_future_slots()
                   11095: 
                   11096: Inputs:
                   11097: 
                   11098: =over 4
                   11099: 
                   11100: cnum - course number
                   11101: 
                   11102: cdom - course domain
                   11103: 
                   11104: now - current UNIX time
                   11105: 
                   11106: symb - optional symb
                   11107: 
                   11108: =back
                   11109: 
                   11110: Returns:
                   11111: 
                   11112: =over 4
                   11113: 
                   11114: sorted_reservable - ref to array of student_schedulable slots currently 
                   11115:                     reservable, ordered by end date of reservation period.
                   11116: 
                   11117: reservable_now - ref to hash of student_schedulable slots currently
                   11118:                  reservable.
                   11119: 
                   11120:     Keys in inner hash are:
                   11121:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11122:     (b) endreserve: end date of reservation period.
                   11123:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11124:         selected.
1.1040    raeburn  11125: 
                   11126: sorted_future - ref to array of student_schedulable slots reservable in
                   11127:                 the future, ordered by start date of reservation period.
                   11128: 
                   11129: future_reservable - ref to hash of student_schedulable slots reservable
                   11130:                     in the future.
                   11131: 
                   11132:     Keys in inner hash are:
                   11133:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11134:     (b) startreserve: start date of reservation period.
                   11135:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11136:         selected.
1.1040    raeburn  11137: 
                   11138: =back
                   11139: 
                   11140: =cut
                   11141: 
                   11142: sub get_future_slots {
                   11143:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11144:     my $map;
                   11145:     if ($symb) {
                   11146:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11147:     }
1.1040    raeburn  11148:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11149:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11150:     foreach my $slot (keys(%slots)) {
                   11151:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11152:         if ($symb) {
1.1229    raeburn  11153:             if ($slots{$slot}->{'symb'} ne '') {
                   11154:                 my $canuse;
                   11155:                 my %oksymbs;
                   11156:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11157:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11158:                 if ($oksymbs{$symb}) {
                   11159:                     $canuse = 1;
                   11160:                 } else {
                   11161:                     foreach my $item (@slotsymbs) {
                   11162:                         if ($item =~ /\.(page|sequence)$/) {
                   11163:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11164:                             if (($map ne '') && ($map eq $sloturl)) {
                   11165:                                 $canuse = 1;
                   11166:                                 last;
                   11167:                             }
                   11168:                         }
                   11169:                     }
                   11170:                 }
                   11171:                 next unless ($canuse);
                   11172:             }
1.1040    raeburn  11173:         }
                   11174:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11175:             ($slots{$slot}->{'endtime'} > $now)) {
                   11176:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11177:                 my $userallowed = 0;
                   11178:                 if ($slots{$slot}->{'allowedsections'}) {
                   11179:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11180:                     if (!defined($env{'request.role.sec'})
                   11181:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11182:                         $userallowed=1;
                   11183:                     } else {
                   11184:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11185:                             $userallowed=1;
                   11186:                         }
                   11187:                     }
                   11188:                     unless ($userallowed) {
                   11189:                         if (defined($env{'request.course.groups'})) {
                   11190:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11191:                             foreach my $group (@groups) {
                   11192:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11193:                                     $userallowed=1;
                   11194:                                     last;
                   11195:                                 }
                   11196:                             }
                   11197:                         }
                   11198:                     }
                   11199:                 }
                   11200:                 if ($slots{$slot}->{'allowedusers'}) {
                   11201:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11202:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11203:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11204:                         $userallowed = 1;
                   11205:                     }
                   11206:                 }
                   11207:                 next unless($userallowed);
                   11208:             }
                   11209:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11210:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11211:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11212:             my $uniqueperiod;
                   11213:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11214:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11215:             }
1.1040    raeburn  11216:             if (($startreserve < $now) &&
                   11217:                 (!$endreserve || $endreserve > $now)) {
                   11218:                 my $lastres = $endreserve;
                   11219:                 if (!$lastres) {
                   11220:                     $lastres = $slots{$slot}->{'starttime'};
                   11221:                 }
                   11222:                 $reservable_now{$slot} = {
                   11223:                                            symb       => $symb,
1.1250    raeburn  11224:                                            endreserve => $lastres,
                   11225:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11226:                                          };
                   11227:             } elsif (($startreserve > $now) &&
                   11228:                      (!$endreserve || $endreserve > $startreserve)) {
                   11229:                 $future_reservable{$slot} = {
                   11230:                                               symb         => $symb,
1.1250    raeburn  11231:                                               startreserve => $startreserve,
                   11232:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11233:                                             };
                   11234:             }
                   11235:         }
                   11236:     }
                   11237:     my @unsorted_reservable = keys(%reservable_now);
                   11238:     if (@unsorted_reservable > 0) {
                   11239:         @sorted_reservable = 
                   11240:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11241:     }
                   11242:     my @unsorted_future = keys(%future_reservable);
                   11243:     if (@unsorted_future > 0) {
                   11244:         @sorted_future =
                   11245:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11246:     }
                   11247:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11248: }
1.780     raeburn  11249: 
                   11250: =pod
                   11251: 
1.1057    foxr     11252: =back
                   11253: 
1.549     albertel 11254: =head1 HTTP Helpers
                   11255: 
                   11256: =over 4
                   11257: 
1.648     raeburn  11258: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11259: 
1.258     albertel 11260: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11261: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11262: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11263: 
                   11264: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11265: $possible_names is an ref to an array of form element names.  As an example:
                   11266: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11267: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11268: 
                   11269: =cut
1.1       albertel 11270: 
1.6       albertel 11271: sub get_unprocessed_cgi {
1.25      albertel 11272:   my ($query,$possible_names)= @_;
1.26      matthew  11273:   # $Apache::lonxml::debug=1;
1.356     albertel 11274:   foreach my $pair (split(/&/,$query)) {
                   11275:     my ($name, $value) = split(/=/,$pair);
1.369     www      11276:     $name = &unescape($name);
1.25      albertel 11277:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11278:       $value =~ tr/+/ /;
                   11279:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11280:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11281:     }
1.16      harris41 11282:   }
1.6       albertel 11283: }
                   11284: 
1.112     bowersj2 11285: =pod
                   11286: 
1.648     raeburn  11287: =item * &cacheheader() 
1.112     bowersj2 11288: 
                   11289: returns cache-controlling header code
                   11290: 
                   11291: =cut
                   11292: 
1.7       albertel 11293: sub cacheheader {
1.258     albertel 11294:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11295:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11296:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11297:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11298:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11299:     return $output;
1.7       albertel 11300: }
                   11301: 
1.112     bowersj2 11302: =pod
                   11303: 
1.648     raeburn  11304: =item * &no_cache($r) 
1.112     bowersj2 11305: 
                   11306: specifies header code to not have cache
                   11307: 
                   11308: =cut
                   11309: 
1.9       albertel 11310: sub no_cache {
1.216     albertel 11311:     my ($r) = @_;
                   11312:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11313: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11314:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11315:     $r->no_cache(1);
                   11316:     $r->header_out("Expires" => $date);
                   11317:     $r->header_out("Pragma" => "no-cache");
1.123     www      11318: }
                   11319: 
                   11320: sub content_type {
1.181     albertel 11321:     my ($r,$type,$charset) = @_;
1.299     foxr     11322:     if ($r) {
                   11323: 	#  Note that printout.pl calls this with undef for $r.
                   11324: 	&no_cache($r);
                   11325:     }
1.258     albertel 11326:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11327:     unless ($charset) {
                   11328: 	$charset=&Apache::lonlocal::current_encoding;
                   11329:     }
                   11330:     if ($charset) { $type.='; charset='.$charset; }
                   11331:     if ($r) {
                   11332: 	$r->content_type($type);
                   11333:     } else {
                   11334: 	print("Content-type: $type\n\n");
                   11335:     }
1.9       albertel 11336: }
1.25      albertel 11337: 
1.112     bowersj2 11338: =pod
                   11339: 
1.648     raeburn  11340: =item * &add_to_env($name,$value) 
1.112     bowersj2 11341: 
1.258     albertel 11342: adds $name to the %env hash with value
1.112     bowersj2 11343: $value, if $name already exists, the entry is converted to an array
                   11344: reference and $value is added to the array.
                   11345: 
                   11346: =cut
                   11347: 
1.25      albertel 11348: sub add_to_env {
                   11349:   my ($name,$value)=@_;
1.258     albertel 11350:   if (defined($env{$name})) {
                   11351:     if (ref($env{$name})) {
1.25      albertel 11352:       #already have multiple values
1.258     albertel 11353:       push(@{ $env{$name} },$value);
1.25      albertel 11354:     } else {
                   11355:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11356:       my $first=$env{$name};
                   11357:       undef($env{$name});
                   11358:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11359:     }
                   11360:   } else {
1.258     albertel 11361:     $env{$name}=$value;
1.25      albertel 11362:   }
1.31      albertel 11363: }
1.149     albertel 11364: 
                   11365: =pod
                   11366: 
1.648     raeburn  11367: =item * &get_env_multiple($name) 
1.149     albertel 11368: 
1.258     albertel 11369: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11370: values may be defined and end up as an array ref.
                   11371: 
                   11372: returns an array of values
                   11373: 
                   11374: =cut
                   11375: 
                   11376: sub get_env_multiple {
                   11377:     my ($name) = @_;
                   11378:     my @values;
1.258     albertel 11379:     if (defined($env{$name})) {
1.149     albertel 11380:         # exists is it an array
1.258     albertel 11381:         if (ref($env{$name})) {
                   11382:             @values=@{ $env{$name} };
1.149     albertel 11383:         } else {
1.258     albertel 11384:             $values[0]=$env{$name};
1.149     albertel 11385:         }
                   11386:     }
                   11387:     return(@values);
                   11388: }
                   11389: 
1.1249    damieng  11390: # Looks at given dependencies, and returns something depending on the context.
                   11391: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11392: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11393: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11394: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11395: # $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.
                   11396: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11397: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11398: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11399: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11400: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11401: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11402: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11403: # @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)
                   11404: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11405: sub ask_for_embedded_content {
1.1249    damieng  11406:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11407:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11408:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11409:         %currsubfile,%unused,$rem);
1.1071    raeburn  11410:     my $counter = 0;
                   11411:     my $numnew = 0;
1.987     raeburn  11412:     my $numremref = 0;
                   11413:     my $numinvalid = 0;
                   11414:     my $numpathchg = 0;
                   11415:     my $numexisting = 0;
1.1071    raeburn  11416:     my $numunused = 0;
                   11417:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11418:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11419:     my $heading = &mt('Upload embedded files');
                   11420:     my $buttontext = &mt('Upload');
                   11421: 
1.1249    damieng  11422:     # fills these variables based on the context:
                   11423:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11424:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11425:     if ($env{'request.course.id'}) {
1.1123    raeburn  11426:         if ($actionurl eq '/adm/dependencies') {
                   11427:             $navmap = Apache::lonnavmaps::navmap->new();
                   11428:         }
                   11429:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11430:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11431:     }
1.1123    raeburn  11432:     if (($actionurl eq '/adm/portfolio') || 
                   11433:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11434:         my $current_path='/';
                   11435:         if ($env{'form.currentpath'}) {
                   11436:             $current_path = $env{'form.currentpath'};
                   11437:         }
                   11438:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11439:             $udom = $cdom;
                   11440:             $uname = $cnum;
1.984     raeburn  11441:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11442:         } else {
                   11443:             $udom = $env{'user.domain'};
                   11444:             $uname = $env{'user.name'};
                   11445:             $url = '/userfiles/portfolio';
                   11446:         }
1.987     raeburn  11447:         $toplevel = $url.'/';
1.984     raeburn  11448:         $url .= $current_path;
                   11449:         $getpropath = 1;
1.987     raeburn  11450:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11451:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11452:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11453:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11454:         $toplevel = $url;
1.984     raeburn  11455:         if ($rest ne '') {
1.987     raeburn  11456:             $url .= $rest;
                   11457:         }
                   11458:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11459:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11460:             $url = $args->{'docs_url'};
                   11461:             $toplevel = $url;
1.1084    raeburn  11462:             if ($args->{'context'} eq 'paste') {
                   11463:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11464:                 ($path) = 
                   11465:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11466:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11467:                 $fileloc =~ s{^/}{};
                   11468:             }
1.1071    raeburn  11469:         }
1.1084    raeburn  11470:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11471:         if ($env{'request.course.id'} ne '') {
                   11472:             if (ref($args) eq 'HASH') {
                   11473:                 $url = $args->{'docs_url'};
                   11474:                 $title = $args->{'docs_title'};
1.1126    raeburn  11475:                 $toplevel = $url; 
                   11476:                 unless ($toplevel =~ m{^/}) {
                   11477:                     $toplevel = "/$url";
                   11478:                 }
1.1085    raeburn  11479:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11480:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11481:                     $path = $1;
                   11482:                 } else {
                   11483:                     ($path) =
                   11484:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11485:                 }
1.1195    raeburn  11486:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11487:                     $fileloc = $toplevel;
                   11488:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11489:                     my ($udom,$uname,$fname) =
                   11490:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11491:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11492:                 } else {
                   11493:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11494:                 }
1.1071    raeburn  11495:                 $fileloc =~ s{^/}{};
                   11496:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11497:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11498:             }
1.987     raeburn  11499:         }
1.1123    raeburn  11500:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11501:         $udom = $cdom;
                   11502:         $uname = $cnum;
                   11503:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11504:         $toplevel = $url;
                   11505:         $path = $url;
                   11506:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11507:         $fileloc =~ s{^/}{};
1.987     raeburn  11508:     }
1.1249    damieng  11509:     
                   11510:     # parses the dependency paths to get some info
                   11511:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11512:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11513:     # (will be completed later)
                   11514:     # $mapping:
                   11515:     #   for external URLs: external URL -> external URL
                   11516:     #   for relative paths: clean path -> original path
                   11517:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11518:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11519:     foreach my $file (keys(%{$allfiles})) {
                   11520:         my $embed_file;
                   11521:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11522:             $embed_file = $1;
                   11523:         } else {
                   11524:             $embed_file = $file;
                   11525:         }
1.1158    raeburn  11526:         my ($absolutepath,$cleaned_file);
                   11527:         if ($embed_file =~ m{^\w+://}) {
                   11528:             $cleaned_file = $embed_file;
1.1147    raeburn  11529:             $newfiles{$cleaned_file} = 1;
                   11530:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11531:         } else {
1.1158    raeburn  11532:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11533:             if ($embed_file =~ m{^/}) {
                   11534:                 $absolutepath = $embed_file;
                   11535:             }
1.1147    raeburn  11536:             if ($cleaned_file =~ m{/}) {
                   11537:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11538:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11539:                 my $item = $fname;
                   11540:                 if ($path ne '') {
                   11541:                     $item = $path.'/'.$fname;
                   11542:                     $subdependencies{$path}{$fname} = 1;
                   11543:                 } else {
                   11544:                     $dependencies{$item} = 1;
                   11545:                 }
                   11546:                 if ($absolutepath) {
                   11547:                     $mapping{$item} = $absolutepath;
                   11548:                 } else {
                   11549:                     $mapping{$item} = $embed_file;
                   11550:                 }
                   11551:             } else {
                   11552:                 $dependencies{$embed_file} = 1;
                   11553:                 if ($absolutepath) {
1.1147    raeburn  11554:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11555:                 } else {
1.1147    raeburn  11556:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11557:                 }
                   11558:             }
1.984     raeburn  11559:         }
                   11560:     }
1.1249    damieng  11561:     
                   11562:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11563:     # and lists
                   11564:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11565:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11566:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11567:     #                                    the path had to be cleaned up
                   11568:     # $existing: hash clean path -> 1 if the file exists
                   11569:     # $numexisting: number of keys in $existing
                   11570:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11571:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11572:     #                                      dependency subdirectories that are
                   11573:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11574:     my $dirptr = 16384;
1.984     raeburn  11575:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11576:         $currsubfile{$path} = {};
1.1123    raeburn  11577:         if (($actionurl eq '/adm/portfolio') || 
                   11578:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11579:             my ($sublistref,$listerror) =
                   11580:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11581:             if (ref($sublistref) eq 'ARRAY') {
                   11582:                 foreach my $line (@{$sublistref}) {
                   11583:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11584:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11585:                 }
1.984     raeburn  11586:             }
1.987     raeburn  11587:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11588:             if (opendir(my $dir,$url.'/'.$path)) {
                   11589:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11590:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11591:             }
1.1084    raeburn  11592:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11593:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11594:                   ($args->{'context'} eq 'paste')) ||
                   11595:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11596:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11597:                 my $dir;
                   11598:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11599:                     $dir = $fileloc;
                   11600:                 } else {
                   11601:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11602:                 }
1.1071    raeburn  11603:                 if ($dir ne '') {
                   11604:                     my ($sublistref,$listerror) =
                   11605:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11606:                     if (ref($sublistref) eq 'ARRAY') {
                   11607:                         foreach my $line (@{$sublistref}) {
                   11608:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11609:                                 undef,$mtime)=split(/\&/,$line,12);
                   11610:                             unless (($testdir&$dirptr) ||
                   11611:                                     ($file_name =~ /^\.\.?$/)) {
                   11612:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11613:                             }
                   11614:                         }
                   11615:                     }
                   11616:                 }
1.984     raeburn  11617:             }
                   11618:         }
                   11619:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11620:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11621:                 my $item = $path.'/'.$file;
                   11622:                 unless ($mapping{$item} eq $item) {
                   11623:                     $pathchanges{$item} = 1;
                   11624:                 }
                   11625:                 $existing{$item} = 1;
                   11626:                 $numexisting ++;
                   11627:             } else {
                   11628:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11629:             }
                   11630:         }
1.1071    raeburn  11631:         if ($actionurl eq '/adm/dependencies') {
                   11632:             foreach my $path (keys(%currsubfile)) {
                   11633:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11634:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11635:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11636:                              next if (($rem ne '') &&
                   11637:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11638:                                        (ref($navmap) &&
                   11639:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11640:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11641:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11642:                              $unused{$path.'/'.$file} = 1; 
                   11643:                          }
                   11644:                     }
                   11645:                 }
                   11646:             }
                   11647:         }
1.984     raeburn  11648:     }
1.1249    damieng  11649:     
                   11650:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11651:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11652:     my %currfile;
1.1123    raeburn  11653:     if (($actionurl eq '/adm/portfolio') ||
                   11654:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11655:         my ($dirlistref,$listerror) =
                   11656:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11657:         if (ref($dirlistref) eq 'ARRAY') {
                   11658:             foreach my $line (@{$dirlistref}) {
                   11659:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11660:                 $currfile{$file_name} = 1;
                   11661:             }
1.984     raeburn  11662:         }
1.987     raeburn  11663:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11664:         if (opendir(my $dir,$url)) {
1.987     raeburn  11665:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11666:             map {$currfile{$_} = 1;} @dir_list;
                   11667:         }
1.1084    raeburn  11668:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11669:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11670:               ($args->{'context'} eq 'paste')) ||
                   11671:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11672:         if ($env{'request.course.id'} ne '') {
                   11673:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11674:             if ($dir ne '') {
                   11675:                 my ($dirlistref,$listerror) =
                   11676:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11677:                 if (ref($dirlistref) eq 'ARRAY') {
                   11678:                     foreach my $line (@{$dirlistref}) {
                   11679:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11680:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11681:                         unless (($testdir&$dirptr) ||
                   11682:                                 ($file_name =~ /^\.\.?$/)) {
                   11683:                             $currfile{$file_name} = [$size,$mtime];
                   11684:                         }
                   11685:                     }
                   11686:                 }
                   11687:             }
                   11688:         }
1.984     raeburn  11689:     }
1.1249    damieng  11690:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11691:     # are not in subdirectories, using $currfile
1.984     raeburn  11692:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11693:         if (exists($currfile{$file})) {
1.987     raeburn  11694:             unless ($mapping{$file} eq $file) {
                   11695:                 $pathchanges{$file} = 1;
                   11696:             }
                   11697:             $existing{$file} = 1;
                   11698:             $numexisting ++;
                   11699:         } else {
1.984     raeburn  11700:             $newfiles{$file} = 1;
                   11701:         }
                   11702:     }
1.1071    raeburn  11703:     foreach my $file (keys(%currfile)) {
                   11704:         unless (($file eq $filename) ||
                   11705:                 ($file eq $filename.'.bak') ||
                   11706:                 ($dependencies{$file})) {
1.1085    raeburn  11707:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11708:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11709:                     next if (($rem ne '') &&
                   11710:                              (($env{"httpref.$rem".$file} ne '') ||
                   11711:                               (ref($navmap) &&
                   11712:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11713:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11714:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11715:                 }
1.1085    raeburn  11716:             }
1.1071    raeburn  11717:             $unused{$file} = 1;
                   11718:         }
                   11719:     }
1.1249    damieng  11720:     
                   11721:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11722:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11723:         ($args->{'context'} eq 'paste')) {
                   11724:         $counter = scalar(keys(%existing));
                   11725:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11726:         return ($output,$counter,$numpathchg,\%existing);
                   11727:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11728:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11729:         $counter = scalar(keys(%existing));
                   11730:         $numpathchg = scalar(keys(%pathchanges));
                   11731:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11732:     }
1.1249    damieng  11733:     
                   11734:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11735:     
                   11736:     # $upload_output: missing dependencies (with upload form)
                   11737:     # $modify_output: uploaded dependencies (in use)
                   11738:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11739:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11740:         if ($actionurl eq '/adm/dependencies') {
                   11741:             next if ($embed_file =~ m{^\w+://});
                   11742:         }
1.660     raeburn  11743:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11744:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11745:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11746:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11747:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11748:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11749:         }
1.1123    raeburn  11750:         $upload_output .= '</td>';
1.1071    raeburn  11751:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11752:             $upload_output.='<td align="right">'.
                   11753:                             '<span class="LC_info LC_fontsize_medium">'.
                   11754:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11755:             $numremref++;
1.660     raeburn  11756:         } elsif ($args->{'error_on_invalid_names'}
                   11757:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11758:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11759:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11760:             $numinvalid++;
1.660     raeburn  11761:         } else {
1.1123    raeburn  11762:             $upload_output .= '<td>'.
                   11763:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11764:                                                      $embed_file,\%mapping,
1.1071    raeburn  11765:                                                      $allfiles,$codebase,'upload');
                   11766:             $counter ++;
                   11767:             $numnew ++;
1.987     raeburn  11768:         }
                   11769:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11770:     }
                   11771:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11772:         if ($actionurl eq '/adm/dependencies') {
                   11773:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11774:             $modify_output .= &start_data_table_row().
                   11775:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11776:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11777:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11778:                               '<td>'.$size.'</td>'.
                   11779:                               '<td>'.$mtime.'</td>'.
                   11780:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11781:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11782:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11783:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11784:                               &embedded_file_element('upload_embedded',$counter,
                   11785:                                                      $embed_file,\%mapping,
                   11786:                                                      $allfiles,$codebase,'modify').
                   11787:                               '</div></td>'.
                   11788:                               &end_data_table_row()."\n";
                   11789:             $counter ++;
                   11790:         } else {
                   11791:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11792:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11793:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11794:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11795:                               &Apache::loncommon::end_data_table_row()."\n";
                   11796:         }
                   11797:     }
                   11798:     my $delidx = $counter;
                   11799:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11800:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11801:         $delete_output .= &start_data_table_row().
                   11802:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11803:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11804:                           '<td>'.$size.'</td>'.
                   11805:                           '<td>'.$mtime.'</td>'.
                   11806:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11807:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11808:                           &embedded_file_element('upload_embedded',$delidx,
                   11809:                                                  $oldfile,\%mapping,$allfiles,
                   11810:                                                  $codebase,'delete').'</td>'.
                   11811:                           &end_data_table_row()."\n"; 
                   11812:         $numunused ++;
                   11813:         $delidx ++;
1.987     raeburn  11814:     }
                   11815:     if ($upload_output) {
                   11816:         $upload_output = &start_data_table().
                   11817:                          $upload_output.
                   11818:                          &end_data_table()."\n";
                   11819:     }
1.1071    raeburn  11820:     if ($modify_output) {
                   11821:         $modify_output = &start_data_table().
                   11822:                          &start_data_table_header_row().
                   11823:                          '<th>'.&mt('File').'</th>'.
                   11824:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11825:                          '<th>'.&mt('Modified').'</th>'.
                   11826:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11827:                          &end_data_table_header_row().
                   11828:                          $modify_output.
                   11829:                          &end_data_table()."\n";
                   11830:     }
                   11831:     if ($delete_output) {
                   11832:         $delete_output = &start_data_table().
                   11833:                          &start_data_table_header_row().
                   11834:                          '<th>'.&mt('File').'</th>'.
                   11835:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11836:                          '<th>'.&mt('Modified').'</th>'.
                   11837:                          '<th>'.&mt('Delete?').'</th>'.
                   11838:                          &end_data_table_header_row().
                   11839:                          $delete_output.
                   11840:                          &end_data_table()."\n";
                   11841:     }
1.987     raeburn  11842:     my $applies = 0;
                   11843:     if ($numremref) {
                   11844:         $applies ++;
                   11845:     }
                   11846:     if ($numinvalid) {
                   11847:         $applies ++;
                   11848:     }
                   11849:     if ($numexisting) {
                   11850:         $applies ++;
                   11851:     }
1.1071    raeburn  11852:     if ($counter || $numunused) {
1.987     raeburn  11853:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11854:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11855:                   $state.'<h3>'.$heading.'</h3>'; 
                   11856:         if ($actionurl eq '/adm/dependencies') {
                   11857:             if ($numnew) {
                   11858:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11859:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11860:                            $upload_output.'<br />'."\n";
                   11861:             }
                   11862:             if ($numexisting) {
                   11863:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11864:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11865:                            $modify_output.'<br />'."\n";
                   11866:                            $buttontext = &mt('Save changes');
                   11867:             }
                   11868:             if ($numunused) {
                   11869:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11870:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11871:                            $delete_output.'<br />'."\n";
                   11872:                            $buttontext = &mt('Save changes');
                   11873:             }
                   11874:         } else {
                   11875:             $output .= $upload_output.'<br />'."\n";
                   11876:         }
                   11877:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11878:                    $counter.'" />'."\n";
                   11879:         if ($actionurl eq '/adm/dependencies') { 
                   11880:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11881:                        $numnew.'" />'."\n";
                   11882:         } elsif ($actionurl eq '') {
1.987     raeburn  11883:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11884:         }
                   11885:     } elsif ($applies) {
                   11886:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11887:         if ($applies > 1) {
                   11888:             $output .=  
1.1123    raeburn  11889:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11890:             if ($numremref) {
                   11891:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11892:             }
                   11893:             if ($numinvalid) {
                   11894:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11895:             }
                   11896:             if ($numexisting) {
                   11897:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11898:             }
                   11899:             $output .= '</ul><br />';
                   11900:         } elsif ($numremref) {
                   11901:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11902:         } elsif ($numinvalid) {
                   11903:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11904:         } elsif ($numexisting) {
                   11905:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11906:         }
                   11907:         $output .= $upload_output.'<br />';
                   11908:     }
                   11909:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11910:     $chgcount = $counter;
1.987     raeburn  11911:     if (keys(%pathchanges) > 0) {
                   11912:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11913:             if ($counter) {
1.987     raeburn  11914:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11915:                                                   $embed_file,\%mapping,
1.1071    raeburn  11916:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11917:             } else {
                   11918:                 $pathchange_output .= 
                   11919:                     &start_data_table_row().
                   11920:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11921:                     $chgcount.'" checked="checked" /></td>'.
                   11922:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11923:                     '<td>'.$embed_file.
                   11924:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11925:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11926:                     '</td>'.&end_data_table_row();
1.660     raeburn  11927:             }
1.987     raeburn  11928:             $numpathchg ++;
                   11929:             $chgcount ++;
1.660     raeburn  11930:         }
                   11931:     }
1.1127    raeburn  11932:     if (($counter) || ($numunused)) {
1.987     raeburn  11933:         if ($numpathchg) {
                   11934:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11935:                        $numpathchg.'" />'."\n";
                   11936:         }
                   11937:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11938:             ($actionurl eq '/adm/imsimport')) {
                   11939:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11940:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11941:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11942:         } elsif ($actionurl eq '/adm/dependencies') {
                   11943:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11944:         }
1.1123    raeburn  11945:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11946:     } elsif ($numpathchg) {
                   11947:         my %pathchange = ();
                   11948:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11949:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11950:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11951:         }
1.987     raeburn  11952:     }
1.1071    raeburn  11953:     return ($output,$counter,$numpathchg);
1.987     raeburn  11954: }
                   11955: 
1.1147    raeburn  11956: =pod
                   11957: 
                   11958: =item * clean_path($name)
                   11959: 
                   11960: Performs clean-up of directories, subdirectories and filename in an
                   11961: embedded object, referenced in an HTML file which is being uploaded
                   11962: to a course or portfolio, where 
                   11963: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11964: checked.
                   11965: 
                   11966: Clean-up is similar to replacements in lonnet::clean_filename()
                   11967: except each / between sub-directory and next level is preserved.
                   11968: 
                   11969: =cut
                   11970: 
                   11971: sub clean_path {
                   11972:     my ($embed_file) = @_;
                   11973:     $embed_file =~s{^/+}{};
                   11974:     my @contents;
                   11975:     if ($embed_file =~ m{/}) {
                   11976:         @contents = split(/\//,$embed_file);
                   11977:     } else {
                   11978:         @contents = ($embed_file);
                   11979:     }
                   11980:     my $lastidx = scalar(@contents)-1;
                   11981:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11982:         $contents[$i]=~s{\\}{/}g;
                   11983:         $contents[$i]=~s/\s+/\_/g;
                   11984:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11985:         if ($i == $lastidx) {
                   11986:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11987:         }
                   11988:     }
                   11989:     if ($lastidx > 0) {
                   11990:         return join('/',@contents);
                   11991:     } else {
                   11992:         return $contents[0];
                   11993:     }
                   11994: }
                   11995: 
1.987     raeburn  11996: sub embedded_file_element {
1.1071    raeburn  11997:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11998:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11999:                    (ref($codebase) eq 'HASH'));
                   12000:     my $output;
1.1071    raeburn  12001:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12002:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12003:     }
                   12004:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12005:                &escape($embed_file).'" />';
                   12006:     unless (($context eq 'upload_embedded') && 
                   12007:             ($mapping->{$embed_file} eq $embed_file)) {
                   12008:         $output .='
                   12009:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12010:     }
                   12011:     my $attrib;
                   12012:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12013:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12014:     }
                   12015:     $output .=
                   12016:         "\n\t\t".
                   12017:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12018:         $attrib.'" />';
                   12019:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12020:         $output .=
                   12021:             "\n\t\t".
                   12022:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12023:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12024:     }
1.987     raeburn  12025:     return $output;
1.660     raeburn  12026: }
                   12027: 
1.1071    raeburn  12028: sub get_dependency_details {
                   12029:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12030:     my ($size,$mtime,$showsize,$showmtime);
                   12031:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12032:         if ($embed_file =~ m{/}) {
                   12033:             my ($path,$fname) = split(/\//,$embed_file);
                   12034:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12035:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12036:             }
                   12037:         } else {
                   12038:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12039:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12040:             }
                   12041:         }
                   12042:         $showsize = $size/1024.0;
                   12043:         $showsize = sprintf("%.1f",$showsize);
                   12044:         if ($mtime > 0) {
                   12045:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12046:         }
                   12047:     }
                   12048:     return ($showsize,$showmtime);
                   12049: }
                   12050: 
                   12051: sub ask_embedded_js {
                   12052:     return <<"END";
                   12053: <script type="text/javascript"">
                   12054: // <![CDATA[
                   12055: function toggleBrowse(counter) {
                   12056:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12057:     var fileid = document.getElementById('embedded_item_'+counter);
                   12058:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12059:     if (chkboxid.checked == true) {
                   12060:         uploaddivid.style.display='block';
                   12061:     } else {
                   12062:         uploaddivid.style.display='none';
                   12063:         fileid.value = '';
                   12064:     }
                   12065: }
                   12066: // ]]>
                   12067: </script>
                   12068: 
                   12069: END
                   12070: }
                   12071: 
1.661     raeburn  12072: sub upload_embedded {
                   12073:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12074:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12075:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12076:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12077:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12078:         my $orig_uploaded_filename =
                   12079:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12080:         foreach my $type ('orig','ref','attrib','codebase') {
                   12081:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12082:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12083:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12084:             }
                   12085:         }
1.661     raeburn  12086:         my ($path,$fname) =
                   12087:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12088:         # no path, whole string is fname
                   12089:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12090:         $fname = &Apache::lonnet::clean_filename($fname);
                   12091:         # See if there is anything left
                   12092:         next if ($fname eq '');
                   12093: 
                   12094:         # Check if file already exists as a file or directory.
                   12095:         my ($state,$msg);
                   12096:         if ($context eq 'portfolio') {
                   12097:             my $port_path = $dirpath;
                   12098:             if ($group ne '') {
                   12099:                 $port_path = "groups/$group/$port_path";
                   12100:             }
1.987     raeburn  12101:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12102:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12103:                                               $dir_root,$port_path,$disk_quota,
                   12104:                                               $current_disk_usage,$uname,$udom);
                   12105:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12106:                 || $state eq 'file_locked') {
1.661     raeburn  12107:                 $output .= $msg;
                   12108:                 next;
                   12109:             }
                   12110:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12111:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12112:             if ($state eq 'exists') {
                   12113:                 $output .= $msg;
                   12114:                 next;
                   12115:             }
                   12116:         }
                   12117:         # Check if extension is valid
                   12118:         if (($fname =~ /\.(\w+)$/) &&
                   12119:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12120:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12121:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12122:             next;
                   12123:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12124:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12125:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12126:             next;
                   12127:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12128:             $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  12129:             next;
                   12130:         }
                   12131:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12132:         my $subdir = $path;
                   12133:         $subdir =~ s{/+$}{};
1.661     raeburn  12134:         if ($context eq 'portfolio') {
1.984     raeburn  12135:             my $result;
                   12136:             if ($state eq 'existingfile') {
                   12137:                 $result=
                   12138:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12139:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12140:             } else {
1.984     raeburn  12141:                 $result=
                   12142:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12143:                                                     $dirpath.
1.1123    raeburn  12144:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12145:                 if ($result !~ m|^/uploaded/|) {
                   12146:                     $output .= '<span class="LC_error">'
                   12147:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12148:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12149:                                .'</span><br />';
                   12150:                     next;
                   12151:                 } else {
1.987     raeburn  12152:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12153:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12154:                 }
1.661     raeburn  12155:             }
1.1123    raeburn  12156:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12157:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12158:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12159:             my $result =
1.1126    raeburn  12160:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12161:             if ($result !~ m|^/uploaded/|) {
                   12162:                 $output .= '<span class="LC_error">'
                   12163:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12164:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12165:                            .'</span><br />';
                   12166:                     next;
                   12167:             } else {
                   12168:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12169:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12170:                 if ($context eq 'syllabus') {
                   12171:                     &Apache::lonnet::make_public_indefinitely($result);
                   12172:                 }
1.987     raeburn  12173:             }
1.661     raeburn  12174:         } else {
                   12175: # Save the file
                   12176:             my $target = $env{'form.embedded_item_'.$i};
                   12177:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12178:             my $dest = $fullpath.$fname;
                   12179:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12180:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12181:             my $count;
                   12182:             my $filepath = $dir_root;
1.1027    raeburn  12183:             foreach my $subdir (@parts) {
                   12184:                 $filepath .= "/$subdir";
                   12185:                 if (!-e $filepath) {
1.661     raeburn  12186:                     mkdir($filepath,0770);
                   12187:                 }
                   12188:             }
                   12189:             my $fh;
                   12190:             if (!open($fh,'>'.$dest)) {
                   12191:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12192:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12193:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12194:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12195:                            '</span><br />';
                   12196:             } else {
                   12197:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12198:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12199:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12200:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12201:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12202:                               '</span><br />';
                   12203:                 } else {
1.987     raeburn  12204:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12205:                                $url.'</span>').'<br />';
                   12206:                     unless ($context eq 'testbank') {
                   12207:                         $footer .= &mt('View embedded file: [_1]',
                   12208:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12209:                     }
                   12210:                 }
                   12211:                 close($fh);
                   12212:             }
                   12213:         }
                   12214:         if ($env{'form.embedded_ref_'.$i}) {
                   12215:             $pathchange{$i} = 1;
                   12216:         }
                   12217:     }
                   12218:     if ($output) {
                   12219:         $output = '<p>'.$output.'</p>';
                   12220:     }
                   12221:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12222:     $returnflag = 'ok';
1.1071    raeburn  12223:     my $numpathchgs = scalar(keys(%pathchange));
                   12224:     if ($numpathchgs > 0) {
1.987     raeburn  12225:         if ($context eq 'portfolio') {
                   12226:             $output .= '<p>'.&mt('or').'</p>';
                   12227:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12228:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12229:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12230:             $returnflag = 'modify_orightml';
                   12231:         }
                   12232:     }
1.1071    raeburn  12233:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12234: }
                   12235: 
                   12236: sub modify_html_form {
                   12237:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12238:     my $end = 0;
                   12239:     my $modifyform;
                   12240:     if ($context eq 'upload_embedded') {
                   12241:         return unless (ref($pathchange) eq 'HASH');
                   12242:         if ($env{'form.number_embedded_items'}) {
                   12243:             $end += $env{'form.number_embedded_items'};
                   12244:         }
                   12245:         if ($env{'form.number_pathchange_items'}) {
                   12246:             $end += $env{'form.number_pathchange_items'};
                   12247:         }
                   12248:         if ($end) {
                   12249:             for (my $i=0; $i<$end; $i++) {
                   12250:                 if ($i < $env{'form.number_embedded_items'}) {
                   12251:                     next unless($pathchange->{$i});
                   12252:                 }
                   12253:                 $modifyform .=
                   12254:                     &start_data_table_row().
                   12255:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12256:                     'checked="checked" /></td>'.
                   12257:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12258:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12259:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12260:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12261:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12262:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12263:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12264:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12265:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12266:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12267:                     &end_data_table_row();
1.1071    raeburn  12268:             }
1.987     raeburn  12269:         }
                   12270:     } else {
                   12271:         $modifyform = $pathchgtable;
                   12272:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12273:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12274:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12275:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12276:         }
                   12277:     }
                   12278:     if ($modifyform) {
1.1071    raeburn  12279:         if ($actionurl eq '/adm/dependencies') {
                   12280:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12281:         }
1.987     raeburn  12282:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12283:                '<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".
                   12284:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12285:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12286:                '</ol></p>'."\n".'<p>'.
                   12287:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12288:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12289:                &start_data_table()."\n".
                   12290:                &start_data_table_header_row().
                   12291:                '<th>'.&mt('Change?').'</th>'.
                   12292:                '<th>'.&mt('Current reference').'</th>'.
                   12293:                '<th>'.&mt('Required reference').'</th>'.
                   12294:                &end_data_table_header_row()."\n".
                   12295:                $modifyform.
                   12296:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12297:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12298:                '</form>'."\n";
                   12299:     }
                   12300:     return;
                   12301: }
                   12302: 
                   12303: sub modify_html_refs {
1.1123    raeburn  12304:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12305:     my $container;
                   12306:     if ($context eq 'portfolio') {
                   12307:         $container = $env{'form.container'};
                   12308:     } elsif ($context eq 'coursedoc') {
                   12309:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12310:     } elsif ($context eq 'manage_dependencies') {
                   12311:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12312:         $container = "/$container";
1.1123    raeburn  12313:     } elsif ($context eq 'syllabus') {
                   12314:         $container = $url;
1.987     raeburn  12315:     } else {
1.1027    raeburn  12316:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12317:     }
                   12318:     my (%allfiles,%codebase,$output,$content);
                   12319:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12320:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12321:         if (wantarray) {
                   12322:             return ('',0,0); 
                   12323:         } else {
                   12324:             return;
                   12325:         }
                   12326:     }
                   12327:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12328:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12329:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12330:             if (wantarray) {
                   12331:                 return ('',0,0);
                   12332:             } else {
                   12333:                 return;
                   12334:             }
                   12335:         } 
1.987     raeburn  12336:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12337:         if ($content eq '-1') {
                   12338:             if (wantarray) {
                   12339:                 return ('',0,0);
                   12340:             } else {
                   12341:                 return;
                   12342:             }
                   12343:         }
1.987     raeburn  12344:     } else {
1.1071    raeburn  12345:         unless ($container =~ /^\Q$dir_root\E/) {
                   12346:             if (wantarray) {
                   12347:                 return ('',0,0);
                   12348:             } else {
                   12349:                 return;
                   12350:             }
                   12351:         } 
1.1317    raeburn  12352:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12353:             $content = join('', <$fh>);
                   12354:             close($fh);
                   12355:         } else {
1.1071    raeburn  12356:             if (wantarray) {
                   12357:                 return ('',0,0);
                   12358:             } else {
                   12359:                 return;
                   12360:             }
1.987     raeburn  12361:         }
                   12362:     }
                   12363:     my ($count,$codebasecount) = (0,0);
                   12364:     my $mm = new File::MMagic;
                   12365:     my $mime_type = $mm->checktype_contents($content);
                   12366:     if ($mime_type eq 'text/html') {
                   12367:         my $parse_result = 
                   12368:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12369:                                                     \%codebase,\$content);
                   12370:         if ($parse_result eq 'ok') {
                   12371:             foreach my $i (@changes) {
                   12372:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12373:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12374:                 if ($allfiles{$ref}) {
                   12375:                     my $newname =  $orig;
                   12376:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12377:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12378:                     if ($attrib_regexp =~ /:/) {
                   12379:                         $attrib_regexp =~ s/\:/|/g;
                   12380:                     }
                   12381:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12382:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12383:                         $count += $numchg;
1.1123    raeburn  12384:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12385:                         delete($allfiles{$ref});
1.987     raeburn  12386:                     }
                   12387:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12388:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12389:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12390:                         $codebasecount ++;
                   12391:                     }
                   12392:                 }
                   12393:             }
1.1123    raeburn  12394:             my $skiprewrites;
1.987     raeburn  12395:             if ($count || $codebasecount) {
                   12396:                 my $saveresult;
1.1071    raeburn  12397:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12398:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12399:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12400:                     if ($url eq $container) {
                   12401:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12402:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12403:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12404:                                             $fname.'</span>').'</p>';
1.987     raeburn  12405:                     } else {
                   12406:                          $output = '<p class="LC_error">'.
                   12407:                                    &mt('Error: update failed for: [_1].',
                   12408:                                    '<span class="LC_filename">'.
                   12409:                                    $container.'</span>').'</p>';
                   12410:                     }
1.1123    raeburn  12411:                     if ($context eq 'syllabus') {
                   12412:                         unless ($saveresult eq 'ok') {
                   12413:                             $skiprewrites = 1;
                   12414:                         }
                   12415:                     }
1.987     raeburn  12416:                 } else {
1.1317    raeburn  12417:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12418:                         print $fh $content;
                   12419:                         close($fh);
                   12420:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12421:                                   $count,'<span class="LC_filename">'.
                   12422:                                   $container.'</span>').'</p>';
1.661     raeburn  12423:                     } else {
1.987     raeburn  12424:                          $output = '<p class="LC_error">'.
                   12425:                                    &mt('Error: could not update [_1].',
                   12426:                                    '<span class="LC_filename">'.
                   12427:                                    $container.'</span>').'</p>';
1.661     raeburn  12428:                     }
                   12429:                 }
                   12430:             }
1.1123    raeburn  12431:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12432:                 my ($actionurl,$state);
                   12433:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12434:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12435:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12436:                                               \%codebase,
                   12437:                                               {'context' => 'rewrites',
                   12438:                                                'ignore_remote_references' => 1,});
                   12439:                 if (ref($mapping) eq 'HASH') {
                   12440:                     my $rewrites = 0;
                   12441:                     foreach my $key (keys(%{$mapping})) {
                   12442:                         next if ($key =~ m{^https?://});
                   12443:                         my $ref = $mapping->{$key};
                   12444:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12445:                         my $attrib;
                   12446:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12447:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12448:                         }
                   12449:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12450:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12451:                             $rewrites += $numchg;
                   12452:                         }
                   12453:                     }
                   12454:                     if ($rewrites) {
                   12455:                         my $saveresult; 
                   12456:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12457:                         if ($url eq $container) {
                   12458:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12459:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12460:                                             $count,'<span class="LC_filename">'.
                   12461:                                             $fname.'</span>').'</p>';
                   12462:                         } else {
                   12463:                             $output .= '<p class="LC_error">'.
                   12464:                                        &mt('Error: could not update links in [_1].',
                   12465:                                        '<span class="LC_filename">'.
                   12466:                                        $container.'</span>').'</p>';
                   12467: 
                   12468:                         }
                   12469:                     }
                   12470:                 }
                   12471:             }
1.987     raeburn  12472:         } else {
                   12473:             &logthis('Failed to parse '.$container.
                   12474:                      ' to modify references: '.$parse_result);
1.661     raeburn  12475:         }
                   12476:     }
1.1071    raeburn  12477:     if (wantarray) {
                   12478:         return ($output,$count,$codebasecount);
                   12479:     } else {
                   12480:         return $output;
                   12481:     }
1.661     raeburn  12482: }
                   12483: 
                   12484: sub check_for_existing {
                   12485:     my ($path,$fname,$element) = @_;
                   12486:     my ($state,$msg);
                   12487:     if (-d $path.'/'.$fname) {
                   12488:         $state = 'exists';
                   12489:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12490:     } elsif (-e $path.'/'.$fname) {
                   12491:         $state = 'exists';
                   12492:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12493:     }
                   12494:     if ($state eq 'exists') {
                   12495:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12496:     }
                   12497:     return ($state,$msg);
                   12498: }
                   12499: 
                   12500: sub check_for_upload {
                   12501:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12502:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12503:     my $filesize = length($env{'form.'.$element});
                   12504:     if (!$filesize) {
                   12505:         my $msg = '<span class="LC_error">'.
                   12506:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12507:                       '<span class="LC_filename">'.$fname.'</span>',
                   12508:                       $filesize).'<br />'.
1.1007    raeburn  12509:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12510:                   '</span>';
                   12511:         return ('zero_bytes',$msg);
                   12512:     }
                   12513:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12514:     my $getpropath = 1;
1.1021    raeburn  12515:     my ($dirlistref,$listerror) =
                   12516:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12517:     my $found_file = 0;
                   12518:     my $locked_file = 0;
1.991     raeburn  12519:     my @lockers;
                   12520:     my $navmap;
                   12521:     if ($env{'request.course.id'}) {
                   12522:         $navmap = Apache::lonnavmaps::navmap->new();
                   12523:     }
1.1021    raeburn  12524:     if (ref($dirlistref) eq 'ARRAY') {
                   12525:         foreach my $line (@{$dirlistref}) {
                   12526:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12527:             if ($file_name eq $fname){
                   12528:                 $file_name = $path.$file_name;
                   12529:                 if ($group ne '') {
                   12530:                     $file_name = $group.$file_name;
                   12531:                 }
                   12532:                 $found_file = 1;
                   12533:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12534:                     foreach my $lock (@lockers) {
                   12535:                         if (ref($lock) eq 'ARRAY') {
                   12536:                             my ($symb,$crsid) = @{$lock};
                   12537:                             if ($crsid eq $env{'request.course.id'}) {
                   12538:                                 if (ref($navmap)) {
                   12539:                                     my $res = $navmap->getBySymb($symb);
                   12540:                                     foreach my $part (@{$res->parts()}) { 
                   12541:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12542:                                         unless (($slot_status == $res->RESERVED) ||
                   12543:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12544:                                             $locked_file = 1;
                   12545:                                         }
1.991     raeburn  12546:                                     }
1.1021    raeburn  12547:                                 } else {
                   12548:                                     $locked_file = 1;
1.991     raeburn  12549:                                 }
                   12550:                             } else {
                   12551:                                 $locked_file = 1;
                   12552:                             }
                   12553:                         }
1.1021    raeburn  12554:                    }
                   12555:                 } else {
                   12556:                     my @info = split(/\&/,$rest);
                   12557:                     my $currsize = $info[6]/1000;
                   12558:                     if ($currsize < $filesize) {
                   12559:                         my $extra = $filesize - $currsize;
                   12560:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12561:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12562:                                       &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   12563:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12564:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12565:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12566:                             return ('will_exceed_quota',$msg);
                   12567:                         }
1.984     raeburn  12568:                     }
                   12569:                 }
1.661     raeburn  12570:             }
                   12571:         }
                   12572:     }
                   12573:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12574:         my $msg = '<p class="LC_warning">'.
                   12575:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12576:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12577:         return ('will_exceed_quota',$msg);
                   12578:     } elsif ($found_file) {
                   12579:         if ($locked_file) {
1.1179    bisitz   12580:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12581:             $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   12582:             $msg .= '</p>';
1.661     raeburn  12583:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12584:             return ('file_locked',$msg);
                   12585:         } else {
1.1179    bisitz   12586:             my $msg = '<p class="LC_error">';
1.984     raeburn  12587:             $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   12588:             $msg .= '</p>';
1.984     raeburn  12589:             return ('existingfile',$msg);
1.661     raeburn  12590:         }
                   12591:     }
                   12592: }
                   12593: 
1.987     raeburn  12594: sub check_for_traversal {
                   12595:     my ($path,$url,$toplevel) = @_;
                   12596:     my @parts=split(/\//,$path);
                   12597:     my $cleanpath;
                   12598:     my $fullpath = $url;
                   12599:     for (my $i=0;$i<@parts;$i++) {
                   12600:         next if ($parts[$i] eq '.');
                   12601:         if ($parts[$i] eq '..') {
                   12602:             $fullpath =~ s{([^/]+/)$}{};
                   12603:         } else {
                   12604:             $fullpath .= $parts[$i].'/';
                   12605:         }
                   12606:     }
                   12607:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12608:         $cleanpath = $1;
                   12609:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12610:         my $curr_toprel = $1;
                   12611:         my @parts = split(/\//,$curr_toprel);
                   12612:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12613:         my @urlparts = split(/\//,$url_toprel);
                   12614:         my $doubledots;
                   12615:         my $startdiff = -1;
                   12616:         for (my $i=0; $i<@urlparts; $i++) {
                   12617:             if ($startdiff == -1) {
                   12618:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12619:                     $startdiff = $i;
                   12620:                     $doubledots .= '../';
                   12621:                 }
                   12622:             } else {
                   12623:                 $doubledots .= '../';
                   12624:             }
                   12625:         }
                   12626:         if ($startdiff > -1) {
                   12627:             $cleanpath = $doubledots;
                   12628:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12629:                 $cleanpath .= $parts[$i].'/';
                   12630:             }
                   12631:         }
                   12632:     }
                   12633:     $cleanpath =~ s{(/)$}{};
                   12634:     return $cleanpath;
                   12635: }
1.31      albertel 12636: 
1.1053    raeburn  12637: sub is_archive_file {
                   12638:     my ($mimetype) = @_;
                   12639:     if (($mimetype eq 'application/octet-stream') ||
                   12640:         ($mimetype eq 'application/x-stuffit') ||
                   12641:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12642:         return 1;
                   12643:     }
                   12644:     return;
                   12645: }
                   12646: 
                   12647: sub decompress_form {
1.1065    raeburn  12648:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12649:     my %lt = &Apache::lonlocal::texthash (
                   12650:         this => 'This file is an archive file.',
1.1067    raeburn  12651:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12652:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12653:         youm => 'You may wish to extract its contents.',
                   12654:         extr => 'Extract contents',
1.1067    raeburn  12655:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12656:         proa => 'Process automatically?',
1.1053    raeburn  12657:         yes  => 'Yes',
                   12658:         no   => 'No',
1.1067    raeburn  12659:         fold => 'Title for folder containing movie',
                   12660:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12661:     );
1.1065    raeburn  12662:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12663:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12664:     my $info = &list_archive_contents($fileloc,\@paths);
                   12665:     if (@paths) {
                   12666:         foreach my $path (@paths) {
                   12667:             $path =~ s{^/}{};
1.1067    raeburn  12668:             if ($path =~ m{^([^/]+)/$}) {
                   12669:                 $topdir = $1;
                   12670:             }
1.1065    raeburn  12671:             if ($path =~ m{^([^/]+)/}) {
                   12672:                 $toplevel{$1} = $path;
                   12673:             } else {
                   12674:                 $toplevel{$path} = $path;
                   12675:             }
                   12676:         }
                   12677:     }
1.1067    raeburn  12678:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12679:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12680:                         "$topdir/media/",
                   12681:                         "$topdir/media/$topdir.mp4",
                   12682:                         "$topdir/media/FirstFrame.png",
                   12683:                         "$topdir/media/player.swf",
                   12684:                         "$topdir/media/swfobject.js",
                   12685:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12686:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12687:                          "$topdir/$topdir.mp4",
                   12688:                          "$topdir/$topdir\_config.xml",
                   12689:                          "$topdir/$topdir\_controller.swf",
                   12690:                          "$topdir/$topdir\_embed.css",
                   12691:                          "$topdir/$topdir\_First_Frame.png",
                   12692:                          "$topdir/$topdir\_player.html",
                   12693:                          "$topdir/$topdir\_Thumbnails.png",
                   12694:                          "$topdir/playerProductInstall.swf",
                   12695:                          "$topdir/scripts/",
                   12696:                          "$topdir/scripts/config_xml.js",
                   12697:                          "$topdir/scripts/handlebars.js",
                   12698:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12699:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12700:                          "$topdir/scripts/modernizr.js",
                   12701:                          "$topdir/scripts/player-min.js",
                   12702:                          "$topdir/scripts/swfobject.js",
                   12703:                          "$topdir/skins/",
                   12704:                          "$topdir/skins/configuration_express.xml",
                   12705:                          "$topdir/skins/express_show/",
                   12706:                          "$topdir/skins/express_show/player-min.css",
                   12707:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12708:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12709:                          "$topdir/$topdir.mp4",
                   12710:                          "$topdir/$topdir\_config.xml",
                   12711:                          "$topdir/$topdir\_controller.swf",
                   12712:                          "$topdir/$topdir\_embed.css",
                   12713:                          "$topdir/$topdir\_First_Frame.png",
                   12714:                          "$topdir/$topdir\_player.html",
                   12715:                          "$topdir/$topdir\_Thumbnails.png",
                   12716:                          "$topdir/playerProductInstall.swf",
                   12717:                          "$topdir/scripts/",
                   12718:                          "$topdir/scripts/config_xml.js",
                   12719:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12720:                          "$topdir/skins/",
                   12721:                          "$topdir/skins/configuration_express.xml",
                   12722:                          "$topdir/skins/express_show/",
                   12723:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12724:                          "$topdir/skins/express_show/spritesheet.png",
                   12725:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12726:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12727:         if (@diffs == 0) {
1.1164    raeburn  12728:             $is_camtasia = 6;
                   12729:         } else {
1.1197    raeburn  12730:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12731:             if (@diffs == 0) {
                   12732:                 $is_camtasia = 8;
1.1197    raeburn  12733:             } else {
                   12734:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12735:                 if (@diffs == 0) {
                   12736:                     $is_camtasia = 8;
                   12737:                 }
1.1164    raeburn  12738:             }
1.1067    raeburn  12739:         }
                   12740:     }
                   12741:     my $output;
                   12742:     if ($is_camtasia) {
                   12743:         $output = <<"ENDCAM";
                   12744: <script type="text/javascript" language="Javascript">
                   12745: // <![CDATA[
                   12746: 
                   12747: function camtasiaToggle() {
                   12748:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12749:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12750:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12751:                 document.getElementById('camtasia_titles').style.display='block';
                   12752:             } else {
                   12753:                 document.getElementById('camtasia_titles').style.display='none';
                   12754:             }
                   12755:         }
                   12756:     }
                   12757:     return;
                   12758: }
                   12759: 
                   12760: // ]]>
                   12761: </script>
                   12762: <p>$lt{'camt'}</p>
                   12763: ENDCAM
1.1065    raeburn  12764:     } else {
1.1067    raeburn  12765:         $output = '<p>'.$lt{'this'};
                   12766:         if ($info eq '') {
                   12767:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12768:         } else {
                   12769:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12770:                        '<div><pre>'.$info.'</pre></div>';
                   12771:         }
1.1065    raeburn  12772:     }
1.1067    raeburn  12773:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12774:     my $duplicates;
                   12775:     my $num = 0;
                   12776:     if (ref($dirlist) eq 'ARRAY') {
                   12777:         foreach my $item (@{$dirlist}) {
                   12778:             if (ref($item) eq 'ARRAY') {
                   12779:                 if (exists($toplevel{$item->[0]})) {
                   12780:                     $duplicates .= 
                   12781:                         &start_data_table_row().
                   12782:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12783:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12784:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12785:                         'value="1" />'.&mt('Yes').'</label>'.
                   12786:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12787:                         '<td>'.$item->[0].'</td>';
                   12788:                     if ($item->[2]) {
                   12789:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12790:                     } else {
                   12791:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12792:                     }
                   12793:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12794:                                    '<td>'.
                   12795:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12796:                                    '</td>'.
                   12797:                                    &end_data_table_row();
                   12798:                     $num ++;
                   12799:                 }
                   12800:             }
                   12801:         }
                   12802:     }
                   12803:     my $itemcount;
                   12804:     if (@paths > 0) {
                   12805:         $itemcount = scalar(@paths);
                   12806:     } else {
                   12807:         $itemcount = 1;
                   12808:     }
1.1067    raeburn  12809:     if ($is_camtasia) {
                   12810:         $output .= $lt{'auto'}.'<br />'.
                   12811:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12812:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12813:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12814:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12815:                    $lt{'no'}.'</label></span><br />'.
                   12816:                    '<div id="camtasia_titles" style="display:block">'.
                   12817:                    &Apache::lonhtmlcommon::start_pick_box().
                   12818:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12819:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12820:                    &Apache::lonhtmlcommon::row_closure().
                   12821:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12822:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12823:                    &Apache::lonhtmlcommon::row_closure(1).
                   12824:                    &Apache::lonhtmlcommon::end_pick_box().
                   12825:                    '</div>';
                   12826:     }
1.1065    raeburn  12827:     $output .= 
                   12828:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12829:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12830:         "\n";
1.1065    raeburn  12831:     if ($duplicates ne '') {
                   12832:         $output .= '<p><span class="LC_warning">'.
                   12833:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12834:                    &start_data_table().
                   12835:                    &start_data_table_header_row().
                   12836:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12837:                    '<th>'.&mt('Name').'</th>'.
                   12838:                    '<th>'.&mt('Type').'</th>'.
                   12839:                    '<th>'.&mt('Size').'</th>'.
                   12840:                    '<th>'.&mt('Last modified').'</th>'.
                   12841:                    &end_data_table_header_row().
                   12842:                    $duplicates.
                   12843:                    &end_data_table().
                   12844:                    '</p>';
                   12845:     }
1.1067    raeburn  12846:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12847:     if (ref($hiddenelements) eq 'HASH') {
                   12848:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12849:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12850:         }
                   12851:     }
                   12852:     $output .= <<"END";
1.1067    raeburn  12853: <br />
1.1053    raeburn  12854: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12855: </form>
                   12856: $noextract
                   12857: END
                   12858:     return $output;
                   12859: }
                   12860: 
1.1065    raeburn  12861: sub decompression_utility {
                   12862:     my ($program) = @_;
                   12863:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12864:     my $location;
                   12865:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12866:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12867:                          '/usr/sbin/') {
                   12868:             if (-x $dir.$program) {
                   12869:                 $location = $dir.$program;
                   12870:                 last;
                   12871:             }
                   12872:         }
                   12873:     }
                   12874:     return $location;
                   12875: }
                   12876: 
                   12877: sub list_archive_contents {
                   12878:     my ($file,$pathsref) = @_;
                   12879:     my (@cmd,$output);
                   12880:     my $needsregexp;
                   12881:     if ($file =~ /\.zip$/) {
                   12882:         @cmd = (&decompression_utility('unzip'),"-l");
                   12883:         $needsregexp = 1;
                   12884:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12885:              ($file =~ /\.tgz$/)) {
                   12886:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12887:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12888:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12889:     } elsif ($file =~ m|\.tar$|) {
                   12890:         @cmd = (&decompression_utility('tar'),"-tf");
                   12891:     }
                   12892:     if (@cmd) {
                   12893:         undef($!);
                   12894:         undef($@);
                   12895:         if (open(my $fh,"-|", @cmd, $file)) {
                   12896:             while (my $line = <$fh>) {
                   12897:                 $output .= $line;
                   12898:                 chomp($line);
                   12899:                 my $item;
                   12900:                 if ($needsregexp) {
                   12901:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12902:                 } else {
                   12903:                     $item = $line;
                   12904:                 }
                   12905:                 if ($item ne '') {
                   12906:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12907:                         push(@{$pathsref},$item);
                   12908:                     } 
                   12909:                 }
                   12910:             }
                   12911:             close($fh);
                   12912:         }
                   12913:     }
                   12914:     return $output;
                   12915: }
                   12916: 
1.1053    raeburn  12917: sub decompress_uploaded_file {
                   12918:     my ($file,$dir) = @_;
                   12919:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12920:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12921:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12922:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12923:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12924:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12925:     my $decompressed = $env{'cgi.decompressed'};
                   12926:     &Apache::lonnet::delenv('cgi.file');
                   12927:     &Apache::lonnet::delenv('cgi.dir');
                   12928:     &Apache::lonnet::delenv('cgi.decompressed');
                   12929:     return ($decompressed,$result);
                   12930: }
                   12931: 
1.1055    raeburn  12932: sub process_decompression {
                   12933:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  12934:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12935:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12936:                &mt('Unexpected file path.').'</p>'."\n";
                   12937:     }
                   12938:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12939:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12940:                &mt('Unexpected course context.').'</p>'."\n";
                   12941:     }
1.1293    raeburn  12942:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  12943:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12944:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12945:     }
1.1055    raeburn  12946:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12947:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12948:         $error = &mt('Filename not a supported archive file type.').
                   12949:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12950:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12951:     } else {
                   12952:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12953:         if ($docuhome eq 'no_host') {
                   12954:             $error = &mt('Could not determine home server for course.');
                   12955:         } else {
                   12956:             my @ids=&Apache::lonnet::current_machine_ids();
                   12957:             my $currdir = "$dir_root/$destination";
                   12958:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12959:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12960:                        "$dir_root/$destination";
                   12961:             } else {
                   12962:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12963:                        "$dir_root/$docudom/$docuname/$destination";
                   12964:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12965:                     $error = &mt('Archive file not found.');
                   12966:                 }
                   12967:             }
1.1065    raeburn  12968:             my (@to_overwrite,@to_skip);
                   12969:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12970:                 my $total = $env{'form.archive_overwrite_total'};
                   12971:                 for (my $i=0; $i<$total; $i++) {
                   12972:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12973:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12974:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12975:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12976:                     }
                   12977:                 }
                   12978:             }
                   12979:             my $numskip = scalar(@to_skip);
1.1292    raeburn  12980:             my $numoverwrite = scalar(@to_overwrite);
                   12981:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  12982:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12983:             } elsif ($dir eq '') {
1.1055    raeburn  12984:                 $error = &mt('Directory containing archive file unavailable.');
                   12985:             } elsif (!$error) {
1.1065    raeburn  12986:                 my ($decompressed,$display);
1.1292    raeburn  12987:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12988:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12989:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  12990:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12991:                         ($decompressed,$display) = 
                   12992:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12993:                         foreach my $item (@to_skip) {
                   12994:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12995:                                 if (-f "$dir/$tempdir/$item") { 
                   12996:                                     unlink("$dir/$tempdir/$item");
                   12997:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  12998:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  12999:                                 }
                   13000:                             }
                   13001:                         }
                   13002:                         foreach my $item (@to_overwrite) {
                   13003:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13004:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13005:                                     if (-f "$dir/$item") {
                   13006:                                         unlink("$dir/$item");
                   13007:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13008:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13009:                                     }
                   13010:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13011:                                 }
1.1065    raeburn  13012:                             }
                   13013:                         }
1.1292    raeburn  13014:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13015:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13016:                         }
1.1065    raeburn  13017:                     }
                   13018:                 } else {
                   13019:                     ($decompressed,$display) = 
                   13020:                         &decompress_uploaded_file($file,$dir);
                   13021:                 }
1.1055    raeburn  13022:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13023:                     $output = '<p class="LC_info">'.
                   13024:                               &mt('Files extracted successfully from archive.').
                   13025:                               '</p>'."\n";
1.1055    raeburn  13026:                     my ($warning,$result,@contents);
                   13027:                     my ($newdirlistref,$newlisterror) =
                   13028:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13029:                                                  $docuname,1);
                   13030:                     my (%is_dir,%changes,@newitems);
                   13031:                     my $dirptr = 16384;
1.1065    raeburn  13032:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13033:                         foreach my $dir_line (@{$newdirlistref}) {
                   13034:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13035:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13036:                                 push(@newitems,$item);
                   13037:                                 if ($dirptr&$testdir) {
                   13038:                                     $is_dir{$item} = 1;
                   13039:                                 }
                   13040:                                 $changes{$item} = 1;
                   13041:                             }
                   13042:                         }
                   13043:                     }
                   13044:                     if (keys(%changes) > 0) {
                   13045:                         foreach my $item (sort(@newitems)) {
                   13046:                             if ($changes{$item}) {
                   13047:                                 push(@contents,$item);
                   13048:                             }
                   13049:                         }
                   13050:                     }
                   13051:                     if (@contents > 0) {
1.1067    raeburn  13052:                         my $wantform;
                   13053:                         unless ($env{'form.autoextract_camtasia'}) {
                   13054:                             $wantform = 1;
                   13055:                         }
1.1056    raeburn  13056:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13057:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13058:                                                                 $currdir,\%is_dir,
                   13059:                                                                 \%children,\%parent,
1.1056    raeburn  13060:                                                                 \@contents,\%dirorder,
                   13061:                                                                 \%titles,$wantform);
1.1055    raeburn  13062:                         if ($datatable ne '') {
                   13063:                             $output .= &archive_options_form('decompressed',$datatable,
                   13064:                                                              $count,$hiddenelem);
1.1065    raeburn  13065:                             my $startcount = 6;
1.1055    raeburn  13066:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13067:                                                            \%titles,\%children);
1.1055    raeburn  13068:                         }
1.1067    raeburn  13069:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13070:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13071:                             my %displayed;
                   13072:                             my $total = 1;
                   13073:                             $env{'form.archive_directory'} = [];
                   13074:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13075:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13076:                                 $path =~ s{/$}{};
                   13077:                                 my $item;
                   13078:                                 if ($path ne '') {
                   13079:                                     $item = "$path/$titles{$i}";
                   13080:                                 } else {
                   13081:                                     $item = $titles{$i};
                   13082:                                 }
                   13083:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13084:                                 if ($item eq $contents[0]) {
                   13085:                                     push(@{$env{'form.archive_directory'}},$i);
                   13086:                                     $env{'form.archive_'.$i} = 'display';
                   13087:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13088:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13089:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13090:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13091:                                     $env{'form.archive_'.$i} = 'display';
                   13092:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13093:                                     $displayed{'web'} = $i;
                   13094:                                 } else {
1.1164    raeburn  13095:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13096:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13097:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13098:                                         push(@{$env{'form.archive_directory'}},$i);
                   13099:                                     }
                   13100:                                     $env{'form.archive_'.$i} = 'dependency';
                   13101:                                 }
                   13102:                                 $total ++;
                   13103:                             }
                   13104:                             for (my $i=1; $i<$total; $i++) {
                   13105:                                 next if ($i == $displayed{'web'});
                   13106:                                 next if ($i == $displayed{'folder'});
                   13107:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13108:                             }
                   13109:                             $env{'form.phase'} = 'decompress_cleanup';
                   13110:                             $env{'form.archivedelete'} = 1;
                   13111:                             $env{'form.archive_count'} = $total-1;
                   13112:                             $output .=
                   13113:                                 &process_extracted_files('coursedocs',$docudom,
                   13114:                                                          $docuname,$destination,
                   13115:                                                          $dir_root,$hiddenelem);
                   13116:                         }
1.1055    raeburn  13117:                     } else {
                   13118:                         $warning = &mt('No new items extracted from archive file.');
                   13119:                     }
                   13120:                 } else {
                   13121:                     $output = $display;
                   13122:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13123:                 }
                   13124:             }
                   13125:         }
                   13126:     }
                   13127:     if ($error) {
                   13128:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13129:                    $error.'</p>'."\n";
                   13130:     }
                   13131:     if ($warning) {
                   13132:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13133:     }
                   13134:     return $output;
                   13135: }
                   13136: 
                   13137: sub get_extracted {
1.1056    raeburn  13138:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13139:         $titles,$wantform) = @_;
1.1055    raeburn  13140:     my $count = 0;
                   13141:     my $depth = 0;
                   13142:     my $datatable;
1.1056    raeburn  13143:     my @hierarchy;
1.1055    raeburn  13144:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13145:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13146:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13147:     foreach my $item (@{$contents}) {
                   13148:         $count ++;
1.1056    raeburn  13149:         @{$dirorder->{$count}} = @hierarchy;
                   13150:         $titles->{$count} = $item;
1.1055    raeburn  13151:         &archive_hierarchy($depth,$count,$parent,$children);
                   13152:         if ($wantform) {
                   13153:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13154:                                        $currdir,$depth,$count);
                   13155:         }
                   13156:         if ($is_dir->{$item}) {
                   13157:             $depth ++;
1.1056    raeburn  13158:             push(@hierarchy,$count);
                   13159:             $parent->{$depth} = $count;
1.1055    raeburn  13160:             $datatable .=
                   13161:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13162:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13163:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13164:             $depth --;
1.1056    raeburn  13165:             pop(@hierarchy);
1.1055    raeburn  13166:         }
                   13167:     }
                   13168:     return ($count,$datatable);
                   13169: }
                   13170: 
                   13171: sub recurse_extracted_archive {
1.1056    raeburn  13172:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13173:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13174:     my $result='';
1.1056    raeburn  13175:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13176:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13177:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13178:         return $result;
                   13179:     }
                   13180:     my $dirptr = 16384;
                   13181:     my ($newdirlistref,$newlisterror) =
                   13182:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13183:     if (ref($newdirlistref) eq 'ARRAY') {
                   13184:         foreach my $dir_line (@{$newdirlistref}) {
                   13185:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13186:             unless ($item =~ /^\.+$/) {
                   13187:                 $$count ++;
1.1056    raeburn  13188:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13189:                 $titles->{$$count} = $item;
1.1055    raeburn  13190:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13191: 
1.1055    raeburn  13192:                 my $is_dir;
                   13193:                 if ($dirptr&$testdir) {
                   13194:                     $is_dir = 1;
                   13195:                 }
                   13196:                 if ($wantform) {
                   13197:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13198:                 }
                   13199:                 if ($is_dir) {
                   13200:                     $$depth ++;
1.1056    raeburn  13201:                     push(@{$hierarchy},$$count);
                   13202:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13203:                     $result .=
                   13204:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13205:                                                    $docuname,$depth,$count,
1.1056    raeburn  13206:                                                    $hierarchy,$dirorder,$children,
                   13207:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13208:                     $$depth --;
1.1056    raeburn  13209:                     pop(@{$hierarchy});
1.1055    raeburn  13210:                 }
                   13211:             }
                   13212:         }
                   13213:     }
                   13214:     return $result;
                   13215: }
                   13216: 
                   13217: sub archive_hierarchy {
                   13218:     my ($depth,$count,$parent,$children) =@_;
                   13219:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13220:         if (exists($parent->{$depth})) {
                   13221:              $children->{$parent->{$depth}} .= $count.':';
                   13222:         }
                   13223:     }
                   13224:     return;
                   13225: }
                   13226: 
                   13227: sub archive_row {
                   13228:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13229:     my ($name) = ($item =~ m{([^/]+)$});
                   13230:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13231:                                        'display'    => 'Add as file',
1.1055    raeburn  13232:                                        'dependency' => 'Include as dependency',
                   13233:                                        'discard'    => 'Discard',
                   13234:                                       );
                   13235:     if ($is_dir) {
1.1059    raeburn  13236:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13237:     }
1.1056    raeburn  13238:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13239:     my $offset = 0;
1.1055    raeburn  13240:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13241:         $offset ++;
1.1065    raeburn  13242:         if ($action ne 'display') {
                   13243:             $offset ++;
                   13244:         }  
1.1055    raeburn  13245:         $output .= '<td><span class="LC_nobreak">'.
                   13246:                    '<label><input type="radio" name="archive_'.$count.
                   13247:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13248:         my $text = $choices{$action};
                   13249:         if ($is_dir) {
                   13250:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13251:             if ($action eq 'display') {
1.1059    raeburn  13252:                 $text = &mt('Add as folder');
1.1055    raeburn  13253:             }
1.1056    raeburn  13254:         } else {
                   13255:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13256: 
                   13257:         }
                   13258:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13259:         if ($action eq 'dependency') {
                   13260:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13261:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13262:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13263:                        '<option value=""></option>'."\n".
                   13264:                        '</select>'."\n".
                   13265:                        '</div>';
1.1059    raeburn  13266:         } elsif ($action eq 'display') {
                   13267:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13268:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13269:                        '</div>';
1.1055    raeburn  13270:         }
1.1056    raeburn  13271:         $output .= '</td>';
1.1055    raeburn  13272:     }
                   13273:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13274:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13275:     for (my $i=0; $i<$depth; $i++) {
                   13276:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13277:     }
                   13278:     if ($is_dir) {
                   13279:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13280:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13281:     } else {
                   13282:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13283:     }
                   13284:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13285:                &end_data_table_row();
                   13286:     return $output;
                   13287: }
                   13288: 
                   13289: sub archive_options_form {
1.1065    raeburn  13290:     my ($form,$display,$count,$hiddenelem) = @_;
                   13291:     my %lt = &Apache::lonlocal::texthash(
                   13292:                perm => 'Permanently remove archive file?',
                   13293:                hows => 'How should each extracted item be incorporated in the course?',
                   13294:                cont => 'Content actions for all',
                   13295:                addf => 'Add as folder/file',
                   13296:                incd => 'Include as dependency for a displayed file',
                   13297:                disc => 'Discard',
                   13298:                no   => 'No',
                   13299:                yes  => 'Yes',
                   13300:                save => 'Save',
                   13301:     );
                   13302:     my $output = <<"END";
                   13303: <form name="$form" method="post" action="">
                   13304: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13305: <label>
                   13306:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13307: </label>
                   13308: &nbsp;
                   13309: <label>
                   13310:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13311: </span>
                   13312: </p>
                   13313: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13314: <br />$lt{'hows'}
                   13315: <div class="LC_columnSection">
                   13316:   <fieldset>
                   13317:     <legend>$lt{'cont'}</legend>
                   13318:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13319:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13320:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13321:   </fieldset>
                   13322: </div>
                   13323: END
                   13324:     return $output.
1.1055    raeburn  13325:            &start_data_table()."\n".
1.1065    raeburn  13326:            $display."\n".
1.1055    raeburn  13327:            &end_data_table()."\n".
                   13328:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13329:            $hiddenelem.
1.1065    raeburn  13330:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13331:            '</form>';
                   13332: }
                   13333: 
                   13334: sub archive_javascript {
1.1056    raeburn  13335:     my ($startcount,$numitems,$titles,$children) = @_;
                   13336:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13337:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13338:     my $scripttag = <<START;
                   13339: <script type="text/javascript">
                   13340: // <![CDATA[
                   13341: 
                   13342: function checkAll(form,prefix) {
                   13343:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13344:     for (var i=0; i < form.elements.length; i++) {
                   13345:         var id = form.elements[i].id;
                   13346:         if ((id != '') && (id != undefined)) {
                   13347:             if (idstr.test(id)) {
                   13348:                 if (form.elements[i].type == 'radio') {
                   13349:                     form.elements[i].checked = true;
1.1056    raeburn  13350:                     var nostart = i-$startcount;
1.1059    raeburn  13351:                     var offset = nostart%7;
                   13352:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13353:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13354:                 }
                   13355:             }
                   13356:         }
                   13357:     }
                   13358: }
                   13359: 
                   13360: function propagateCheck(form,count) {
                   13361:     if (count > 0) {
1.1059    raeburn  13362:         var startelement = $startcount + ((count-1) * 7);
                   13363:         for (var j=1; j<6; j++) {
                   13364:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13365:                 var item = startelement + j; 
                   13366:                 if (form.elements[item].type == 'radio') {
                   13367:                     if (form.elements[item].checked) {
                   13368:                         containerCheck(form,count,j);
                   13369:                         break;
                   13370:                     }
1.1055    raeburn  13371:                 }
                   13372:             }
                   13373:         }
                   13374:     }
                   13375: }
                   13376: 
                   13377: numitems = $numitems
1.1056    raeburn  13378: var titles = new Array(numitems);
                   13379: var parents = new Array(numitems);
1.1055    raeburn  13380: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13381:     parents[i] = new Array;
1.1055    raeburn  13382: }
1.1059    raeburn  13383: var maintitle = '$maintitle';
1.1055    raeburn  13384: 
                   13385: START
                   13386: 
1.1056    raeburn  13387:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13388:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13389:         for (my $i=0; $i<@contents; $i ++) {
                   13390:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13391:         }
                   13392:     }
                   13393: 
1.1056    raeburn  13394:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13395:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13396:     }
                   13397: 
1.1055    raeburn  13398:     $scripttag .= <<END;
                   13399: 
                   13400: function containerCheck(form,count,offset) {
                   13401:     if (count > 0) {
1.1056    raeburn  13402:         dependencyCheck(form,count,offset);
1.1059    raeburn  13403:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13404:         form.elements[item].checked = true;
                   13405:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13406:             if (parents[count].length > 0) {
                   13407:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13408:                     containerCheck(form,parents[count][j],offset);
                   13409:                 }
                   13410:             }
                   13411:         }
                   13412:     }
                   13413: }
                   13414: 
                   13415: function dependencyCheck(form,count,offset) {
                   13416:     if (count > 0) {
1.1059    raeburn  13417:         var chosen = (offset+$startcount)+7*(count-1);
                   13418:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13419:         var currtype = form.elements[depitem].type;
                   13420:         if (form.elements[chosen].value == 'dependency') {
                   13421:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13422:             form.elements[depitem].options.length = 0;
                   13423:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13424:             for (var i=1; i<=numitems; i++) {
                   13425:                 if (i == count) {
                   13426:                     continue;
                   13427:                 }
1.1059    raeburn  13428:                 var startelement = $startcount + (i-1) * 7;
                   13429:                 for (var j=1; j<6; j++) {
                   13430:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13431:                         var item = startelement + j;
                   13432:                         if (form.elements[item].type == 'radio') {
                   13433:                             if (form.elements[item].checked) {
                   13434:                                 if (form.elements[item].value == 'display') {
                   13435:                                     var n = form.elements[depitem].options.length;
                   13436:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13437:                                 }
                   13438:                             }
                   13439:                         }
                   13440:                     }
                   13441:                 }
                   13442:             }
                   13443:         } else {
                   13444:             document.getElementById('arc_depon_'+count).style.display='none';
                   13445:             form.elements[depitem].options.length = 0;
                   13446:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13447:         }
1.1059    raeburn  13448:         titleCheck(form,count,offset);
1.1056    raeburn  13449:     }
                   13450: }
                   13451: 
                   13452: function propagateSelect(form,count,offset) {
                   13453:     if (count > 0) {
1.1065    raeburn  13454:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13455:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13456:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13457:             if (parents[count].length > 0) {
                   13458:                 for (var j=0; j<parents[count].length; j++) {
                   13459:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13460:                 }
                   13461:             }
                   13462:         }
                   13463:     }
                   13464: }
1.1056    raeburn  13465: 
                   13466: function containerSelect(form,count,offset,picked) {
                   13467:     if (count > 0) {
1.1065    raeburn  13468:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13469:         if (form.elements[item].type == 'radio') {
                   13470:             if (form.elements[item].value == 'dependency') {
                   13471:                 if (form.elements[item+1].type == 'select-one') {
                   13472:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13473:                         if (form.elements[item+1].options[i].value == picked) {
                   13474:                             form.elements[item+1].selectedIndex = i;
                   13475:                             break;
                   13476:                         }
                   13477:                     }
                   13478:                 }
                   13479:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13480:                     if (parents[count].length > 0) {
                   13481:                         for (var j=0; j<parents[count].length; j++) {
                   13482:                             containerSelect(form,parents[count][j],offset,picked);
                   13483:                         }
                   13484:                     }
                   13485:                 }
                   13486:             }
                   13487:         }
                   13488:     }
                   13489: }
                   13490: 
1.1059    raeburn  13491: function titleCheck(form,count,offset) {
                   13492:     if (count > 0) {
                   13493:         var chosen = (offset+$startcount)+7*(count-1);
                   13494:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13495:         var currtype = form.elements[depitem].type;
                   13496:         if (form.elements[chosen].value == 'display') {
                   13497:             document.getElementById('arc_title_'+count).style.display='block';
                   13498:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13499:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13500:             }
                   13501:         } else {
                   13502:             document.getElementById('arc_title_'+count).style.display='none';
                   13503:             if (currtype == 'text') { 
                   13504:                 document.getElementById('archive_title_'+count).value='';
                   13505:             }
                   13506:         }
                   13507:     }
                   13508:     return;
                   13509: }
                   13510: 
1.1055    raeburn  13511: // ]]>
                   13512: </script>
                   13513: END
                   13514:     return $scripttag;
                   13515: }
                   13516: 
                   13517: sub process_extracted_files {
1.1067    raeburn  13518:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13519:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13520:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13521:     my @ids=&Apache::lonnet::current_machine_ids();
                   13522:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13523:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13524:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13525:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13526:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13527:         $pathtocheck = "$dir_root/$destination";
                   13528:         $dir = $dir_root;
                   13529:         $ishome = 1;
                   13530:     } else {
                   13531:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13532:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13533:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13534:     }
                   13535:     my $currdir = "$dir_root/$destination";
                   13536:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13537:     if ($env{'form.folderpath'}) {
                   13538:         my @items = split('&',$env{'form.folderpath'});
                   13539:         $folders{'0'} = $items[-2];
1.1099    raeburn  13540:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13541:             $containers{'0'}='page';
                   13542:         } else {  
                   13543:             $containers{'0'}='sequence';
                   13544:         }
1.1055    raeburn  13545:     }
                   13546:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13547:     if ($numitems) {
                   13548:         for (my $i=1; $i<=$numitems; $i++) {
                   13549:             my $path = $env{'form.archive_content_'.$i};
                   13550:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13551:                 my $item = $1;
                   13552:                 $toplevelitems{$item} = $i;
                   13553:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13554:                     $is_dir{$item} = 1;
                   13555:                 }
                   13556:             }
                   13557:         }
                   13558:     }
1.1067    raeburn  13559:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13560:     if (keys(%toplevelitems) > 0) {
                   13561:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13562:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13563:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13564:     }
1.1066    raeburn  13565:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13566:     if ($numitems) {
                   13567:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13568:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13569:             my $path = $env{'form.archive_content_'.$i};
                   13570:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13571:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13572:                     if ($prefix ne '' && $path ne '') {
                   13573:                         if (-e $prefix.$path) {
1.1066    raeburn  13574:                             if ((@archdirs > 0) && 
                   13575:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13576:                                 $todeletedir{$prefix.$path} = 1;
                   13577:                             } else {
                   13578:                                 $todelete{$prefix.$path} = 1;
                   13579:                             }
1.1055    raeburn  13580:                         }
                   13581:                     }
                   13582:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13583:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13584:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13585:                     $docstitle = $env{'form.archive_title_'.$i};
                   13586:                     if ($docstitle eq '') {
                   13587:                         $docstitle = $title;
                   13588:                     }
1.1055    raeburn  13589:                     $outer = 0;
1.1056    raeburn  13590:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13591:                         if (@{$dirorder{$i}} > 0) {
                   13592:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13593:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13594:                                     $outer = $item;
                   13595:                                     last;
                   13596:                                 }
                   13597:                             }
                   13598:                         }
                   13599:                     }
                   13600:                     my ($errtext,$fatal) = 
                   13601:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13602:                                                '/'.$folders{$outer}.'.'.
                   13603:                                                $containers{$outer});
                   13604:                     next if ($fatal);
                   13605:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13606:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13607:                             $mapinner{$i} = time;
1.1055    raeburn  13608:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13609:                             $containers{$i} = 'sequence';
                   13610:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13611:                                       $folders{$i}.'.'.$containers{$i};
                   13612:                             my $newidx = &LONCAPA::map::getresidx();
                   13613:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13614:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13615:                             push(@LONCAPA::map::order,$newidx);
                   13616:                             my ($outtext,$errtext) =
                   13617:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13618:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13619:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13620:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13621:                             unless ($errtext) {
1.1294    raeburn  13622:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13623:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13624:                                             '</li>'."\n";
1.1067    raeburn  13625:                             }
1.1055    raeburn  13626:                         }
                   13627:                     } else {
                   13628:                         if ($context eq 'coursedocs') {
                   13629:                             my $newidx=&LONCAPA::map::getresidx();
                   13630:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13631:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13632:                                       $title;
1.1294    raeburn  13633:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13634:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13635:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13636:                                 }
                   13637:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13638:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13639:                                 }
                   13640:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13641:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13642:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13643:                                         unless ($ishome) {
                   13644:                                             my $fetch = "$newdest{$i}/$title";
                   13645:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13646:                                             $prompttofetch{$fetch} = 1;
                   13647:                                         }
1.1292    raeburn  13648:                                     }
1.1067    raeburn  13649:                                 }
1.1294    raeburn  13650:                                 $LONCAPA::map::resources[$newidx]=
                   13651:                                     $docstitle.':'.$url.':false:normal:res';
                   13652:                                 push(@LONCAPA::map::order, $newidx);
                   13653:                                 my ($outtext,$errtext)=
                   13654:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13655:                                                             $docuname.'/'.$folders{$outer}.
                   13656:                                                             '.'.$containers{$outer},1,1);
                   13657:                                 unless ($errtext) {
                   13658:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13659:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13660:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13661:                                                    '</li>'."\n";
                   13662:                                     }
1.1067    raeburn  13663:                                 }
1.1294    raeburn  13664:                             } else {
                   13665:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13666:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13667:                             }
1.1055    raeburn  13668:                         }
                   13669:                     }
1.1086    raeburn  13670:                 }
                   13671:             } else {
1.1294    raeburn  13672:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13673:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13674:             }
                   13675:         }
                   13676:         for (my $i=1; $i<=$numitems; $i++) {
                   13677:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13678:             my $path = $env{'form.archive_content_'.$i};
                   13679:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13680:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13681:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13682:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13683:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13684:                         my ($itemidx,$fullpath,$relpath);
                   13685:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13686:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13687:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13688:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13689:                                     $itemidx = $j;
1.1056    raeburn  13690:                                 }
                   13691:                             }
1.1086    raeburn  13692:                         }
                   13693:                         if ($itemidx eq '') {
                   13694:                             $itemidx =  0;
                   13695:                         } 
                   13696:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13697:                             if ($mapinner{$referrer{$i}}) {
                   13698:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13699:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13700:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13701:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13702:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13703:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13704:                                             if (!-e $fullpath) {
                   13705:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13706:                                             }
                   13707:                                         }
1.1086    raeburn  13708:                                     } else {
                   13709:                                         last;
1.1056    raeburn  13710:                                     }
1.1086    raeburn  13711:                                 }
                   13712:                             }
                   13713:                         } elsif ($newdest{$referrer{$i}}) {
                   13714:                             $fullpath = $newdest{$referrer{$i}};
                   13715:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13716:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13717:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13718:                                     last;
                   13719:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13720:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13721:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13722:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13723:                                         if (!-e $fullpath) {
                   13724:                                             mkdir($fullpath,0755);
1.1056    raeburn  13725:                                         }
                   13726:                                     }
1.1086    raeburn  13727:                                 } else {
                   13728:                                     last;
1.1056    raeburn  13729:                                 }
1.1055    raeburn  13730:                             }
                   13731:                         }
1.1086    raeburn  13732:                         if ($fullpath ne '') {
                   13733:                             if (-e "$prefix$path") {
1.1292    raeburn  13734:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13735:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13736:                                 }
1.1086    raeburn  13737:                             }
                   13738:                             if (-e "$fullpath/$title") {
                   13739:                                 my $showpath;
                   13740:                                 if ($relpath ne '') {
                   13741:                                     $showpath = "$relpath/$title";
                   13742:                                 } else {
                   13743:                                     $showpath = "/$title";
                   13744:                                 } 
1.1294    raeburn  13745:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13746:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13747:                                            '</li>'."\n";
1.1292    raeburn  13748:                                 unless ($ishome) {
                   13749:                                     my $fetch = "$fullpath/$title";
                   13750:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   13751:                                     $prompttofetch{$fetch} = 1;
                   13752:                                 }
1.1086    raeburn  13753:                             }
                   13754:                         }
1.1055    raeburn  13755:                     }
1.1086    raeburn  13756:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13757:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  13758:                                     &HTML::Entities::encode($path,'<>&"'),
                   13759:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13760:                                 '<br />';
1.1055    raeburn  13761:                 }
                   13762:             } else {
1.1294    raeburn  13763:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  13764:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13765:             }
                   13766:         }
                   13767:         if (keys(%todelete)) {
                   13768:             foreach my $key (keys(%todelete)) {
                   13769:                 unlink($key);
1.1066    raeburn  13770:             }
                   13771:         }
                   13772:         if (keys(%todeletedir)) {
                   13773:             foreach my $key (keys(%todeletedir)) {
                   13774:                 rmdir($key);
                   13775:             }
                   13776:         }
                   13777:         foreach my $dir (sort(keys(%is_dir))) {
                   13778:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13779:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13780:             }
                   13781:         }
1.1067    raeburn  13782:         if ($result ne '') {
                   13783:             $output .= '<ul>'."\n".
                   13784:                        $result."\n".
                   13785:                        '</ul>';
                   13786:         }
                   13787:         unless ($ishome) {
                   13788:             my $replicationfail;
                   13789:             foreach my $item (keys(%prompttofetch)) {
                   13790:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13791:                 unless ($fetchresult eq 'ok') {
                   13792:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13793:                 }
                   13794:             }
                   13795:             if ($replicationfail) {
                   13796:                 $output .= '<p class="LC_error">'.
                   13797:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13798:                            $replicationfail.
                   13799:                            '</ul></p>';
                   13800:             }
                   13801:         }
1.1055    raeburn  13802:     } else {
                   13803:         $warning = &mt('No items found in archive.');
                   13804:     }
                   13805:     if ($error) {
                   13806:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13807:                    $error.'</p>'."\n";
                   13808:     }
                   13809:     if ($warning) {
                   13810:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13811:     }
                   13812:     return $output;
                   13813: }
                   13814: 
1.1066    raeburn  13815: sub cleanup_empty_dirs {
                   13816:     my ($path) = @_;
                   13817:     if (($path ne '') && (-d $path)) {
                   13818:         if (opendir(my $dirh,$path)) {
                   13819:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13820:             my $numitems = 0;
                   13821:             foreach my $item (@dircontents) {
                   13822:                 if (-d "$path/$item") {
1.1111    raeburn  13823:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13824:                     if (-e "$path/$item") {
                   13825:                         $numitems ++;
                   13826:                     }
                   13827:                 } else {
                   13828:                     $numitems ++;
                   13829:                 }
                   13830:             }
                   13831:             if ($numitems == 0) {
                   13832:                 rmdir($path);
                   13833:             }
                   13834:             closedir($dirh);
                   13835:         }
                   13836:     }
                   13837:     return;
                   13838: }
                   13839: 
1.41      ng       13840: =pod
1.45      matthew  13841: 
1.1162    raeburn  13842: =item * &get_folder_hierarchy()
1.1068    raeburn  13843: 
                   13844: Provides hierarchy of names of folders/sub-folders containing the current
                   13845: item,
                   13846: 
                   13847: Inputs: 3
                   13848:      - $navmap - navmaps object
                   13849: 
                   13850:      - $map - url for map (either the trigger itself, or map containing
                   13851:                            the resource, which is the trigger).
                   13852: 
                   13853:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13854: 
                   13855: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13856: 
                   13857: =cut
                   13858: 
                   13859: sub get_folder_hierarchy {
                   13860:     my ($navmap,$map,$showitem) = @_;
                   13861:     my @pathitems;
                   13862:     if (ref($navmap)) {
                   13863:         my $mapres = $navmap->getResourceByUrl($map);
                   13864:         if (ref($mapres)) {
                   13865:             my $pcslist = $mapres->map_hierarchy();
                   13866:             if ($pcslist ne '') {
                   13867:                 my @pcs = split(/,/,$pcslist);
                   13868:                 foreach my $pc (@pcs) {
                   13869:                     if ($pc == 1) {
1.1129    raeburn  13870:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13871:                     } else {
                   13872:                         my $res = $navmap->getByMapPc($pc);
                   13873:                         if (ref($res)) {
                   13874:                             my $title = $res->compTitle();
                   13875:                             $title =~ s/\W+/_/g;
                   13876:                             if ($title ne '') {
                   13877:                                 push(@pathitems,$title);
                   13878:                             }
                   13879:                         }
                   13880:                     }
                   13881:                 }
                   13882:             }
1.1071    raeburn  13883:             if ($showitem) {
                   13884:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13885:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13886:                 } else {
                   13887:                     my $maptitle = $mapres->compTitle();
                   13888:                     $maptitle =~ s/\W+/_/g;
                   13889:                     if ($maptitle ne '') {
                   13890:                         push(@pathitems,$maptitle);
                   13891:                     }
1.1068    raeburn  13892:                 }
                   13893:             }
                   13894:         }
                   13895:     }
                   13896:     return @pathitems;
                   13897: }
                   13898: 
                   13899: =pod
                   13900: 
1.1015    raeburn  13901: =item * &get_turnedin_filepath()
                   13902: 
                   13903: Determines path in a user's portfolio file for storage of files uploaded
                   13904: to a specific essayresponse or dropbox item.
                   13905: 
                   13906: Inputs: 3 required + 1 optional.
                   13907: $symb is symb for resource, $uname and $udom are for current user (required).
                   13908: $caller is optional (can be "submission", if routine is called when storing
                   13909: an upoaded file when "Submit Answer" button was pressed).
                   13910: 
                   13911: Returns array containing $path and $multiresp. 
                   13912: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13913: than one file upload item.  Callers of routine should append partid as a 
                   13914: subdirectory to $path in cases where $multiresp is 1.
                   13915: 
                   13916: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13917: 
                   13918: =cut
                   13919: 
                   13920: sub get_turnedin_filepath {
                   13921:     my ($symb,$uname,$udom,$caller) = @_;
                   13922:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13923:     my $turnindir;
                   13924:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13925:     $turnindir = $userhash{'turnindir'};
                   13926:     my ($path,$multiresp);
                   13927:     if ($turnindir eq '') {
                   13928:         if ($caller eq 'submission') {
                   13929:             $turnindir = &mt('turned in');
                   13930:             $turnindir =~ s/\W+/_/g;
                   13931:             my %newhash = (
                   13932:                             'turnindir' => $turnindir,
                   13933:                           );
                   13934:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13935:         }
                   13936:     }
                   13937:     if ($turnindir ne '') {
                   13938:         $path = '/'.$turnindir.'/';
                   13939:         my ($multipart,$turnin,@pathitems);
                   13940:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13941:         if (defined($navmap)) {
                   13942:             my $mapres = $navmap->getResourceByUrl($map);
                   13943:             if (ref($mapres)) {
                   13944:                 my $pcslist = $mapres->map_hierarchy();
                   13945:                 if ($pcslist ne '') {
                   13946:                     foreach my $pc (split(/,/,$pcslist)) {
                   13947:                         my $res = $navmap->getByMapPc($pc);
                   13948:                         if (ref($res)) {
                   13949:                             my $title = $res->compTitle();
                   13950:                             $title =~ s/\W+/_/g;
                   13951:                             if ($title ne '') {
1.1149    raeburn  13952:                                 if (($pc > 1) && (length($title) > 12)) {
                   13953:                                     $title = substr($title,0,12);
                   13954:                                 }
1.1015    raeburn  13955:                                 push(@pathitems,$title);
                   13956:                             }
                   13957:                         }
                   13958:                     }
                   13959:                 }
                   13960:                 my $maptitle = $mapres->compTitle();
                   13961:                 $maptitle =~ s/\W+/_/g;
                   13962:                 if ($maptitle ne '') {
1.1149    raeburn  13963:                     if (length($maptitle) > 12) {
                   13964:                         $maptitle = substr($maptitle,0,12);
                   13965:                     }
1.1015    raeburn  13966:                     push(@pathitems,$maptitle);
                   13967:                 }
                   13968:                 unless ($env{'request.state'} eq 'construct') {
                   13969:                     my $res = $navmap->getBySymb($symb);
                   13970:                     if (ref($res)) {
                   13971:                         my $partlist = $res->parts();
                   13972:                         my $totaluploads = 0;
                   13973:                         if (ref($partlist) eq 'ARRAY') {
                   13974:                             foreach my $part (@{$partlist}) {
                   13975:                                 my @types = $res->responseType($part);
                   13976:                                 my @ids = $res->responseIds($part);
                   13977:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13978:                                     if ($types[$i] eq 'essay') {
                   13979:                                         my $partid = $part.'_'.$ids[$i];
                   13980:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13981:                                             $totaluploads ++;
                   13982:                                         }
                   13983:                                     }
                   13984:                                 }
                   13985:                             }
                   13986:                             if ($totaluploads > 1) {
                   13987:                                 $multiresp = 1;
                   13988:                             }
                   13989:                         }
                   13990:                     }
                   13991:                 }
                   13992:             } else {
                   13993:                 return;
                   13994:             }
                   13995:         } else {
                   13996:             return;
                   13997:         }
                   13998:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13999:         $restitle =~ s/\W+/_/g;
                   14000:         if ($restitle eq '') {
                   14001:             $restitle = ($resurl =~ m{/[^/]+$});
                   14002:             if ($restitle eq '') {
                   14003:                 $restitle = time;
                   14004:             }
                   14005:         }
1.1149    raeburn  14006:         if (length($restitle) > 12) {
                   14007:             $restitle = substr($restitle,0,12);
                   14008:         }
1.1015    raeburn  14009:         push(@pathitems,$restitle);
                   14010:         $path .= join('/',@pathitems);
                   14011:     }
                   14012:     return ($path,$multiresp);
                   14013: }
                   14014: 
                   14015: =pod
                   14016: 
1.464     albertel 14017: =back
1.41      ng       14018: 
1.112     bowersj2 14019: =head1 CSV Upload/Handling functions
1.38      albertel 14020: 
1.41      ng       14021: =over 4
                   14022: 
1.648     raeburn  14023: =item * &upfile_store($r)
1.41      ng       14024: 
                   14025: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14026: needs $env{'form.upfile'}
1.41      ng       14027: returns $datatoken to be put into hidden field
                   14028: 
                   14029: =cut
1.31      albertel 14030: 
                   14031: sub upfile_store {
                   14032:     my $r=shift;
1.258     albertel 14033:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14034:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14035:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14036:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14037: 
1.1299    raeburn  14038:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14039:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14040:                                      time.'_'.$$);
                   14041:     return if ($datatoken eq '');
                   14042: 
1.31      albertel 14043:     {
1.158     raeburn  14044:         my $datafile = $r->dir_config('lonDaemons').
                   14045:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14046:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14047:             print $fh $env{'form.upfile'};
1.158     raeburn  14048:             close($fh);
                   14049:         }
1.31      albertel 14050:     }
                   14051:     return $datatoken;
                   14052: }
                   14053: 
1.56      matthew  14054: =pod
                   14055: 
1.1290    raeburn  14056: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14057: 
                   14058: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14059: $datatoken is the name to assign to the temporary file.
1.258     albertel 14060: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14061: 
                   14062: =cut
1.31      albertel 14063: 
                   14064: sub load_tmp_file {
1.1290    raeburn  14065:     my ($r,$datatoken) = @_;
                   14066:     return if ($datatoken eq '');
1.31      albertel 14067:     my @studentdata=();
                   14068:     {
1.158     raeburn  14069:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14070:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14071:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14072:             @studentdata=<$fh>;
                   14073:             close($fh);
                   14074:         }
1.31      albertel 14075:     }
1.258     albertel 14076:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14077: }
                   14078: 
1.1290    raeburn  14079: sub valid_datatoken {
                   14080:     my ($datatoken) = @_;
1.1325    raeburn  14081:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14082:         return $datatoken;
                   14083:     }
                   14084:     return;
                   14085: }
                   14086: 
1.56      matthew  14087: =pod
                   14088: 
1.648     raeburn  14089: =item * &upfile_record_sep()
1.41      ng       14090: 
                   14091: Separate uploaded file into records
                   14092: returns array of records,
1.258     albertel 14093: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14094: 
                   14095: =cut
1.31      albertel 14096: 
                   14097: sub upfile_record_sep {
1.258     albertel 14098:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14099:     } else {
1.248     albertel 14100: 	my @records;
1.258     albertel 14101: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14102: 	    if ($line=~/^\s*$/) { next; }
                   14103: 	    push(@records,$line);
                   14104: 	}
                   14105: 	return @records;
1.31      albertel 14106:     }
                   14107: }
                   14108: 
1.56      matthew  14109: =pod
                   14110: 
1.648     raeburn  14111: =item * &record_sep($record)
1.41      ng       14112: 
1.258     albertel 14113: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14114: 
                   14115: =cut
                   14116: 
1.263     www      14117: sub takeleft {
                   14118:     my $index=shift;
                   14119:     return substr('0000'.$index,-4,4);
                   14120: }
                   14121: 
1.31      albertel 14122: sub record_sep {
                   14123:     my $record=shift;
                   14124:     my %components=();
1.258     albertel 14125:     if ($env{'form.upfiletype'} eq 'xml') {
                   14126:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14127:         my $i=0;
1.356     albertel 14128:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14129:             $field=~s/^(\"|\')//;
                   14130:             $field=~s/(\"|\')$//;
1.263     www      14131:             $components{&takeleft($i)}=$field;
1.31      albertel 14132:             $i++;
                   14133:         }
1.258     albertel 14134:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14135:         my $i=0;
1.356     albertel 14136:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14137:             $field=~s/^(\"|\')//;
                   14138:             $field=~s/(\"|\')$//;
1.263     www      14139:             $components{&takeleft($i)}=$field;
1.31      albertel 14140:             $i++;
                   14141:         }
                   14142:     } else {
1.561     www      14143:         my $separator=',';
1.480     banghart 14144:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14145:             $separator=';';
1.480     banghart 14146:         }
1.31      albertel 14147:         my $i=0;
1.561     www      14148: # the character we are looking for to indicate the end of a quote or a record 
                   14149:         my $looking_for=$separator;
                   14150: # do not add the characters to the fields
                   14151:         my $ignore=0;
                   14152: # we just encountered a separator (or the beginning of the record)
                   14153:         my $just_found_separator=1;
                   14154: # store the field we are working on here
                   14155:         my $field='';
                   14156: # work our way through all characters in record
                   14157:         foreach my $character ($record=~/(.)/g) {
                   14158:             if ($character eq $looking_for) {
                   14159:                if ($character ne $separator) {
                   14160: # Found the end of a quote, again looking for separator
                   14161:                   $looking_for=$separator;
                   14162:                   $ignore=1;
                   14163:                } else {
                   14164: # Found a separator, store away what we got
                   14165:                   $components{&takeleft($i)}=$field;
                   14166: 	          $i++;
                   14167:                   $just_found_separator=1;
                   14168:                   $ignore=0;
                   14169:                   $field='';
                   14170:                }
                   14171:                next;
                   14172:             }
                   14173: # single or double quotation marks after a separator indicate beginning of a quote
                   14174: # we are now looking for the end of the quote and need to ignore separators
                   14175:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14176:                $looking_for=$character;
                   14177:                next;
                   14178:             }
                   14179: # ignore would be true after we reached the end of a quote
                   14180:             if ($ignore) { next; }
                   14181:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14182:             $field.=$character;
                   14183:             $just_found_separator=0; 
1.31      albertel 14184:         }
1.561     www      14185: # catch the very last entry, since we never encountered the separator
                   14186:         $components{&takeleft($i)}=$field;
1.31      albertel 14187:     }
                   14188:     return %components;
                   14189: }
                   14190: 
1.144     matthew  14191: ######################################################
                   14192: ######################################################
                   14193: 
1.56      matthew  14194: =pod
                   14195: 
1.648     raeburn  14196: =item * &upfile_select_html()
1.41      ng       14197: 
1.144     matthew  14198: Return HTML code to select a file from the users machine and specify 
                   14199: the file type.
1.41      ng       14200: 
                   14201: =cut
                   14202: 
1.144     matthew  14203: ######################################################
                   14204: ######################################################
1.31      albertel 14205: sub upfile_select_html {
1.144     matthew  14206:     my %Types = (
                   14207:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14208:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14209:                  space => &mt('Space separated'),
                   14210:                  tab   => &mt('Tabulator separated'),
                   14211: #                 xml   => &mt('HTML/XML'),
                   14212:                  );
                   14213:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14214:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14215:     foreach my $type (sort(keys(%Types))) {
                   14216:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14217:     }
                   14218:     $Str .= "</select>\n";
                   14219:     return $Str;
1.31      albertel 14220: }
                   14221: 
1.301     albertel 14222: sub get_samples {
                   14223:     my ($records,$toget) = @_;
                   14224:     my @samples=({});
                   14225:     my $got=0;
                   14226:     foreach my $rec (@$records) {
                   14227: 	my %temp = &record_sep($rec);
                   14228: 	if (! grep(/\S/, values(%temp))) { next; }
                   14229: 	if (%temp) {
                   14230: 	    $samples[$got]=\%temp;
                   14231: 	    $got++;
                   14232: 	    if ($got == $toget) { last; }
                   14233: 	}
                   14234:     }
                   14235:     return \@samples;
                   14236: }
                   14237: 
1.144     matthew  14238: ######################################################
                   14239: ######################################################
                   14240: 
1.56      matthew  14241: =pod
                   14242: 
1.648     raeburn  14243: =item * &csv_print_samples($r,$records)
1.41      ng       14244: 
                   14245: Prints a table of sample values from each column uploaded $r is an
                   14246: Apache Request ref, $records is an arrayref from
                   14247: &Apache::loncommon::upfile_record_sep
                   14248: 
                   14249: =cut
                   14250: 
1.144     matthew  14251: ######################################################
                   14252: ######################################################
1.31      albertel 14253: sub csv_print_samples {
                   14254:     my ($r,$records) = @_;
1.662     bisitz   14255:     my $samples = &get_samples($records,5);
1.301     albertel 14256: 
1.594     raeburn  14257:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14258:               &start_data_table_header_row());
1.356     albertel 14259:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14260:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14261:     $r->print(&end_data_table_header_row());
1.301     albertel 14262:     foreach my $hash (@$samples) {
1.594     raeburn  14263: 	$r->print(&start_data_table_row());
1.356     albertel 14264: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14265: 	    $r->print('<td>');
1.356     albertel 14266: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14267: 	    $r->print('</td>');
                   14268: 	}
1.594     raeburn  14269: 	$r->print(&end_data_table_row());
1.31      albertel 14270:     }
1.594     raeburn  14271:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14272: }
                   14273: 
1.144     matthew  14274: ######################################################
                   14275: ######################################################
                   14276: 
1.56      matthew  14277: =pod
                   14278: 
1.648     raeburn  14279: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14280: 
                   14281: Prints a table to create associations between values and table columns.
1.144     matthew  14282: 
1.41      ng       14283: $r is an Apache Request ref,
                   14284: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14285: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14286: 
                   14287: =cut
                   14288: 
1.144     matthew  14289: ######################################################
                   14290: ######################################################
1.31      albertel 14291: sub csv_print_select_table {
                   14292:     my ($r,$records,$d) = @_;
1.301     albertel 14293:     my $i=0;
                   14294:     my $samples = &get_samples($records,1);
1.144     matthew  14295:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14296: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14297:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14298:               '<th>'.&mt('Column').'</th>'.
                   14299:               &end_data_table_header_row()."\n");
1.356     albertel 14300:     foreach my $array_ref (@$d) {
                   14301: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14302: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14303: 
1.875     bisitz   14304: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14305: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14306: 	$r->print('<option value="none"></option>');
1.356     albertel 14307: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14308: 	    $r->print('<option value="'.$sample.'"'.
                   14309:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14310:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14311: 	}
1.594     raeburn  14312: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14313: 	$i++;
                   14314:     }
1.594     raeburn  14315:     $r->print(&end_data_table());
1.31      albertel 14316:     $i--;
                   14317:     return $i;
                   14318: }
1.56      matthew  14319: 
1.144     matthew  14320: ######################################################
                   14321: ######################################################
                   14322: 
1.56      matthew  14323: =pod
1.31      albertel 14324: 
1.648     raeburn  14325: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14326: 
                   14327: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14328: 
                   14329: $r is an Apache Request ref,
                   14330: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14331: $d is an array of 2 element arrays (internal name, displayed name)
                   14332: 
                   14333: =cut
                   14334: 
1.144     matthew  14335: ######################################################
                   14336: ######################################################
1.31      albertel 14337: sub csv_samples_select_table {
                   14338:     my ($r,$records,$d) = @_;
                   14339:     my $i=0;
1.144     matthew  14340:     #
1.662     bisitz   14341:     my $max_samples = 5;
                   14342:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14343:     $r->print(&start_data_table().
                   14344:               &start_data_table_header_row().'<th>'.
                   14345:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14346:               &end_data_table_header_row());
1.301     albertel 14347: 
                   14348:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14349: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14350: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14351: 	foreach my $option (@$d) {
                   14352: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14353: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14354:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14355:                       $display.'</option>');
1.31      albertel 14356: 	}
                   14357: 	$r->print('</select></td><td>');
1.662     bisitz   14358: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14359: 	    if (defined($samples->[$line]{$key})) { 
                   14360: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14361: 	    }
                   14362: 	}
1.594     raeburn  14363: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14364: 	$i++;
                   14365:     }
1.594     raeburn  14366:     $r->print(&end_data_table());
1.31      albertel 14367:     $i--;
                   14368:     return($i);
1.115     matthew  14369: }
                   14370: 
1.144     matthew  14371: ######################################################
                   14372: ######################################################
                   14373: 
1.115     matthew  14374: =pod
                   14375: 
1.648     raeburn  14376: =item * &clean_excel_name($name)
1.115     matthew  14377: 
                   14378: Returns a replacement for $name which does not contain any illegal characters.
                   14379: 
                   14380: =cut
                   14381: 
1.144     matthew  14382: ######################################################
                   14383: ######################################################
1.115     matthew  14384: sub clean_excel_name {
                   14385:     my ($name) = @_;
                   14386:     $name =~ s/[:\*\?\/\\]//g;
                   14387:     if (length($name) > 31) {
                   14388:         $name = substr($name,0,31);
                   14389:     }
                   14390:     return $name;
1.25      albertel 14391: }
1.84      albertel 14392: 
1.85      albertel 14393: =pod
                   14394: 
1.648     raeburn  14395: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14396: 
                   14397: Returns either 1 or undef
                   14398: 
                   14399: 1 if the part is to be hidden, undef if it is to be shown
                   14400: 
                   14401: Arguments are:
                   14402: 
                   14403: $id the id of the part to be checked
                   14404: $symb, optional the symb of the resource to check
                   14405: $udom, optional the domain of the user to check for
                   14406: $uname, optional the username of the user to check for
                   14407: 
                   14408: =cut
1.84      albertel 14409: 
                   14410: sub check_if_partid_hidden {
                   14411:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14412:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14413: 					 $symb,$udom,$uname);
1.141     albertel 14414:     my $truth=1;
                   14415:     #if the string starts with !, then the list is the list to show not hide
                   14416:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14417:     my @hiddenlist=split(/,/,$hiddenparts);
                   14418:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14419: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14420:     }
1.141     albertel 14421:     return !$truth;
1.84      albertel 14422: }
1.127     matthew  14423: 
1.138     matthew  14424: 
                   14425: ############################################################
                   14426: ############################################################
                   14427: 
                   14428: =pod
                   14429: 
1.157     matthew  14430: =back 
                   14431: 
1.138     matthew  14432: =head1 cgi-bin script and graphing routines
                   14433: 
1.157     matthew  14434: =over 4
                   14435: 
1.648     raeburn  14436: =item * &get_cgi_id()
1.138     matthew  14437: 
                   14438: Inputs: none
                   14439: 
                   14440: Returns an id which can be used to pass environment variables
                   14441: to various cgi-bin scripts.  These environment variables will
                   14442: be removed from the users environment after a given time by
                   14443: the routine &Apache::lonnet::transfer_profile_to_env.
                   14444: 
                   14445: =cut
                   14446: 
                   14447: ############################################################
                   14448: ############################################################
1.152     albertel 14449: my $uniq=0;
1.136     matthew  14450: sub get_cgi_id {
1.154     albertel 14451:     $uniq=($uniq+1)%100000;
1.280     albertel 14452:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14453: }
                   14454: 
1.127     matthew  14455: ############################################################
                   14456: ############################################################
                   14457: 
                   14458: =pod
                   14459: 
1.648     raeburn  14460: =item * &DrawBarGraph()
1.127     matthew  14461: 
1.138     matthew  14462: Facilitates the plotting of data in a (stacked) bar graph.
                   14463: Puts plot definition data into the users environment in order for 
                   14464: graph.png to plot it.  Returns an <img> tag for the plot.
                   14465: The bars on the plot are labeled '1','2',...,'n'.
                   14466: 
                   14467: Inputs:
                   14468: 
                   14469: =over 4
                   14470: 
                   14471: =item $Title: string, the title of the plot
                   14472: 
                   14473: =item $xlabel: string, text describing the X-axis of the plot
                   14474: 
                   14475: =item $ylabel: string, text describing the Y-axis of the plot
                   14476: 
                   14477: =item $Max: scalar, the maximum Y value to use in the plot
                   14478: If $Max is < any data point, the graph will not be rendered.
                   14479: 
1.140     matthew  14480: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14481: they are plotted.  If undefined, default values will be used.
                   14482: 
1.178     matthew  14483: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14484: 
1.138     matthew  14485: =item @Values: An array of array references.  Each array reference holds data
                   14486: to be plotted in a stacked bar chart.
                   14487: 
1.239     matthew  14488: =item If the final element of @Values is a hash reference the key/value
                   14489: pairs will be added to the graph definition.
                   14490: 
1.138     matthew  14491: =back
                   14492: 
                   14493: Returns:
                   14494: 
                   14495: An <img> tag which references graph.png and the appropriate identifying
                   14496: information for the plot.
                   14497: 
1.127     matthew  14498: =cut
                   14499: 
                   14500: ############################################################
                   14501: ############################################################
1.134     matthew  14502: sub DrawBarGraph {
1.178     matthew  14503:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14504:     #
                   14505:     if (! defined($colors)) {
                   14506:         $colors = ['#33ff00', 
                   14507:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14508:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14509:                   ]; 
                   14510:     }
1.228     matthew  14511:     my $extra_settings = {};
                   14512:     if (ref($Values[-1]) eq 'HASH') {
                   14513:         $extra_settings = pop(@Values);
                   14514:     }
1.127     matthew  14515:     #
1.136     matthew  14516:     my $identifier = &get_cgi_id();
                   14517:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14518:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14519:         return '';
                   14520:     }
1.225     matthew  14521:     #
                   14522:     my @Labels;
                   14523:     if (defined($labels)) {
                   14524:         @Labels = @$labels;
                   14525:     } else {
                   14526:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14527:             push(@Labels,$i+1);
1.225     matthew  14528:         }
                   14529:     }
                   14530:     #
1.129     matthew  14531:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14532:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14533:     my %ValuesHash;
                   14534:     my $NumSets=1;
                   14535:     foreach my $array (@Values) {
                   14536:         next if (! ref($array));
1.136     matthew  14537:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14538:             join(',',@$array);
1.129     matthew  14539:     }
1.127     matthew  14540:     #
1.136     matthew  14541:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14542:     if ($NumBars < 3) {
                   14543:         $width = 120+$NumBars*32;
1.220     matthew  14544:         $xskip = 1;
1.225     matthew  14545:         $bar_width = 30;
                   14546:     } elsif ($NumBars < 5) {
                   14547:         $width = 120+$NumBars*20;
                   14548:         $xskip = 1;
                   14549:         $bar_width = 20;
1.220     matthew  14550:     } elsif ($NumBars < 10) {
1.136     matthew  14551:         $width = 120+$NumBars*15;
                   14552:         $xskip = 1;
                   14553:         $bar_width = 15;
                   14554:     } elsif ($NumBars <= 25) {
                   14555:         $width = 120+$NumBars*11;
                   14556:         $xskip = 5;
                   14557:         $bar_width = 8;
                   14558:     } elsif ($NumBars <= 50) {
                   14559:         $width = 120+$NumBars*8;
                   14560:         $xskip = 5;
                   14561:         $bar_width = 4;
                   14562:     } else {
                   14563:         $width = 120+$NumBars*8;
                   14564:         $xskip = 5;
                   14565:         $bar_width = 4;
                   14566:     }
                   14567:     #
1.137     matthew  14568:     $Max = 1 if ($Max < 1);
                   14569:     if ( int($Max) < $Max ) {
                   14570:         $Max++;
                   14571:         $Max = int($Max);
                   14572:     }
1.127     matthew  14573:     $Title  = '' if (! defined($Title));
                   14574:     $xlabel = '' if (! defined($xlabel));
                   14575:     $ylabel = '' if (! defined($ylabel));
1.369     www      14576:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14577:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14578:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14579:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14580:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14581:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14582:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14583:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14584:     $ValuesHash{$id.'.height'}   = $height;
                   14585:     $ValuesHash{$id.'.width'}    = $width;
                   14586:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14587:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14588:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14589:     #
1.228     matthew  14590:     # Deal with other parameters
                   14591:     while (my ($key,$value) = each(%$extra_settings)) {
                   14592:         $ValuesHash{$id.'.'.$key} = $value;
                   14593:     }
                   14594:     #
1.646     raeburn  14595:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14596:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14597: }
                   14598: 
                   14599: ############################################################
                   14600: ############################################################
                   14601: 
                   14602: =pod
                   14603: 
1.648     raeburn  14604: =item * &DrawXYGraph()
1.137     matthew  14605: 
1.138     matthew  14606: Facilitates the plotting of data in an XY graph.
                   14607: Puts plot definition data into the users environment in order for 
                   14608: graph.png to plot it.  Returns an <img> tag for the plot.
                   14609: 
                   14610: Inputs:
                   14611: 
                   14612: =over 4
                   14613: 
                   14614: =item $Title: string, the title of the plot
                   14615: 
                   14616: =item $xlabel: string, text describing the X-axis of the plot
                   14617: 
                   14618: =item $ylabel: string, text describing the Y-axis of the plot
                   14619: 
                   14620: =item $Max: scalar, the maximum Y value to use in the plot
                   14621: If $Max is < any data point, the graph will not be rendered.
                   14622: 
                   14623: =item $colors: Array ref containing the hex color codes for the data to be 
                   14624: plotted in.  If undefined, default values will be used.
                   14625: 
                   14626: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14627: 
                   14628: =item $Ydata: Array ref containing Array refs.  
1.185     www      14629: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14630: 
                   14631: =item %Values: hash indicating or overriding any default values which are 
                   14632: passed to graph.png.  
                   14633: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14634: 
                   14635: =back
                   14636: 
                   14637: Returns:
                   14638: 
                   14639: An <img> tag which references graph.png and the appropriate identifying
                   14640: information for the plot.
                   14641: 
1.137     matthew  14642: =cut
                   14643: 
                   14644: ############################################################
                   14645: ############################################################
                   14646: sub DrawXYGraph {
                   14647:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14648:     #
                   14649:     # Create the identifier for the graph
                   14650:     my $identifier = &get_cgi_id();
                   14651:     my $id = 'cgi.'.$identifier;
                   14652:     #
                   14653:     $Title  = '' if (! defined($Title));
                   14654:     $xlabel = '' if (! defined($xlabel));
                   14655:     $ylabel = '' if (! defined($ylabel));
                   14656:     my %ValuesHash = 
                   14657:         (
1.369     www      14658:          $id.'.title'  => &escape($Title),
                   14659:          $id.'.xlabel' => &escape($xlabel),
                   14660:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14661:          $id.'.y_max_value'=> $Max,
                   14662:          $id.'.labels'     => join(',',@$Xlabels),
                   14663:          $id.'.PlotType'   => 'XY',
                   14664:          );
                   14665:     #
                   14666:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14667:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14668:     }
                   14669:     #
                   14670:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14671:         return '';
                   14672:     }
                   14673:     my $NumSets=1;
1.138     matthew  14674:     foreach my $array (@{$Ydata}){
1.137     matthew  14675:         next if (! ref($array));
                   14676:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14677:     }
1.138     matthew  14678:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14679:     #
                   14680:     # Deal with other parameters
                   14681:     while (my ($key,$value) = each(%Values)) {
                   14682:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14683:     }
                   14684:     #
1.646     raeburn  14685:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14686:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14687: }
                   14688: 
                   14689: ############################################################
                   14690: ############################################################
                   14691: 
                   14692: =pod
                   14693: 
1.648     raeburn  14694: =item * &DrawXYYGraph()
1.138     matthew  14695: 
                   14696: Facilitates the plotting of data in an XY graph with two Y axes.
                   14697: Puts plot definition data into the users environment in order for 
                   14698: graph.png to plot it.  Returns an <img> tag for the plot.
                   14699: 
                   14700: Inputs:
                   14701: 
                   14702: =over 4
                   14703: 
                   14704: =item $Title: string, the title of the plot
                   14705: 
                   14706: =item $xlabel: string, text describing the X-axis of the plot
                   14707: 
                   14708: =item $ylabel: string, text describing the Y-axis of the plot
                   14709: 
                   14710: =item $colors: Array ref containing the hex color codes for the data to be 
                   14711: plotted in.  If undefined, default values will be used.
                   14712: 
                   14713: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14714: 
                   14715: =item $Ydata1: The first data set
                   14716: 
                   14717: =item $Min1: The minimum value of the left Y-axis
                   14718: 
                   14719: =item $Max1: The maximum value of the left Y-axis
                   14720: 
                   14721: =item $Ydata2: The second data set
                   14722: 
                   14723: =item $Min2: The minimum value of the right Y-axis
                   14724: 
                   14725: =item $Max2: The maximum value of the left Y-axis
                   14726: 
                   14727: =item %Values: hash indicating or overriding any default values which are 
                   14728: passed to graph.png.  
                   14729: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14730: 
                   14731: =back
                   14732: 
                   14733: Returns:
                   14734: 
                   14735: An <img> tag which references graph.png and the appropriate identifying
                   14736: information for the plot.
1.136     matthew  14737: 
                   14738: =cut
                   14739: 
                   14740: ############################################################
                   14741: ############################################################
1.137     matthew  14742: sub DrawXYYGraph {
                   14743:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14744:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14745:     #
                   14746:     # Create the identifier for the graph
                   14747:     my $identifier = &get_cgi_id();
                   14748:     my $id = 'cgi.'.$identifier;
                   14749:     #
                   14750:     $Title  = '' if (! defined($Title));
                   14751:     $xlabel = '' if (! defined($xlabel));
                   14752:     $ylabel = '' if (! defined($ylabel));
                   14753:     my %ValuesHash = 
                   14754:         (
1.369     www      14755:          $id.'.title'  => &escape($Title),
                   14756:          $id.'.xlabel' => &escape($xlabel),
                   14757:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14758:          $id.'.labels' => join(',',@$Xlabels),
                   14759:          $id.'.PlotType' => 'XY',
                   14760:          $id.'.NumSets' => 2,
1.137     matthew  14761:          $id.'.two_axes' => 1,
                   14762:          $id.'.y1_max_value' => $Max1,
                   14763:          $id.'.y1_min_value' => $Min1,
                   14764:          $id.'.y2_max_value' => $Max2,
                   14765:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14766:          );
                   14767:     #
1.137     matthew  14768:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14769:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14770:     }
                   14771:     #
                   14772:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14773:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14774:         return '';
                   14775:     }
                   14776:     my $NumSets=1;
1.137     matthew  14777:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14778:         next if (! ref($array));
                   14779:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14780:     }
                   14781:     #
                   14782:     # Deal with other parameters
                   14783:     while (my ($key,$value) = each(%Values)) {
                   14784:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14785:     }
                   14786:     #
1.646     raeburn  14787:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14788:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14789: }
                   14790: 
                   14791: ############################################################
                   14792: ############################################################
                   14793: 
                   14794: =pod
                   14795: 
1.157     matthew  14796: =back 
                   14797: 
1.139     matthew  14798: =head1 Statistics helper routines?  
                   14799: 
                   14800: Bad place for them but what the hell.
                   14801: 
1.157     matthew  14802: =over 4
                   14803: 
1.648     raeburn  14804: =item * &chartlink()
1.139     matthew  14805: 
                   14806: Returns a link to the chart for a specific student.  
                   14807: 
                   14808: Inputs:
                   14809: 
                   14810: =over 4
                   14811: 
                   14812: =item $linktext: The text of the link
                   14813: 
                   14814: =item $sname: The students username
                   14815: 
                   14816: =item $sdomain: The students domain
                   14817: 
                   14818: =back
                   14819: 
1.157     matthew  14820: =back
                   14821: 
1.139     matthew  14822: =cut
                   14823: 
                   14824: ############################################################
                   14825: ############################################################
                   14826: sub chartlink {
                   14827:     my ($linktext, $sname, $sdomain) = @_;
                   14828:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14829:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14830:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14831:        '">'.$linktext.'</a>';
1.153     matthew  14832: }
                   14833: 
                   14834: #######################################################
                   14835: #######################################################
                   14836: 
                   14837: =pod
                   14838: 
                   14839: =head1 Course Environment Routines
1.157     matthew  14840: 
                   14841: =over 4
1.153     matthew  14842: 
1.648     raeburn  14843: =item * &restore_course_settings()
1.153     matthew  14844: 
1.648     raeburn  14845: =item * &store_course_settings()
1.153     matthew  14846: 
                   14847: Restores/Store indicated form parameters from the course environment.
                   14848: Will not overwrite existing values of the form parameters.
                   14849: 
                   14850: Inputs: 
                   14851: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14852: 
                   14853: a hash ref describing the data to be stored.  For example:
                   14854:    
                   14855: %Save_Parameters = ('Status' => 'scalar',
                   14856:     'chartoutputmode' => 'scalar',
                   14857:     'chartoutputdata' => 'scalar',
                   14858:     'Section' => 'array',
1.373     raeburn  14859:     'Group' => 'array',
1.153     matthew  14860:     'StudentData' => 'array',
                   14861:     'Maps' => 'array');
                   14862: 
                   14863: Returns: both routines return nothing
                   14864: 
1.631     raeburn  14865: =back
                   14866: 
1.153     matthew  14867: =cut
                   14868: 
                   14869: #######################################################
                   14870: #######################################################
                   14871: sub store_course_settings {
1.496     albertel 14872:     return &store_settings($env{'request.course.id'},@_);
                   14873: }
                   14874: 
                   14875: sub store_settings {
1.153     matthew  14876:     # save to the environment
                   14877:     # appenv the same items, just to be safe
1.300     albertel 14878:     my $udom  = $env{'user.domain'};
                   14879:     my $uname = $env{'user.name'};
1.496     albertel 14880:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14881:     my %SaveHash;
                   14882:     my %AppHash;
                   14883:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14884:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14885:         my $envname = 'environment.'.$basename;
1.258     albertel 14886:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14887:             # Save this value away
                   14888:             if ($type eq 'scalar' &&
1.258     albertel 14889:                 (! exists($env{$envname}) || 
                   14890:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14891:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14892:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14893:             } elsif ($type eq 'array') {
                   14894:                 my $stored_form;
1.258     albertel 14895:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14896:                     $stored_form = join(',',
                   14897:                                         map {
1.369     www      14898:                                             &escape($_);
1.258     albertel 14899:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14900:                 } else {
                   14901:                     $stored_form = 
1.369     www      14902:                         &escape($env{'form.'.$setting});
1.153     matthew  14903:                 }
                   14904:                 # Determine if the array contents are the same.
1.258     albertel 14905:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14906:                     $SaveHash{$basename} = $stored_form;
                   14907:                     $AppHash{$envname}   = $stored_form;
                   14908:                 }
                   14909:             }
                   14910:         }
                   14911:     }
                   14912:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14913:                                           $udom,$uname);
1.153     matthew  14914:     if ($put_result !~ /^(ok|delayed)/) {
                   14915:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14916:                                  'got error:'.$put_result);
                   14917:     }
                   14918:     # Make sure these settings stick around in this session, too
1.646     raeburn  14919:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14920:     return;
                   14921: }
                   14922: 
                   14923: sub restore_course_settings {
1.499     albertel 14924:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14925: }
                   14926: 
                   14927: sub restore_settings {
                   14928:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14929:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14930:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14931:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14932:             '.'.$setting;
1.258     albertel 14933:         if (exists($env{$envname})) {
1.153     matthew  14934:             if ($type eq 'scalar') {
1.258     albertel 14935:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14936:             } elsif ($type eq 'array') {
1.258     albertel 14937:                 $env{'form.'.$setting} = [ 
1.153     matthew  14938:                                            map { 
1.369     www      14939:                                                &unescape($_); 
1.258     albertel 14940:                                            } split(',',$env{$envname})
1.153     matthew  14941:                                            ];
                   14942:             }
                   14943:         }
                   14944:     }
1.127     matthew  14945: }
                   14946: 
1.618     raeburn  14947: #######################################################
                   14948: #######################################################
                   14949: 
                   14950: =pod
                   14951: 
                   14952: =head1 Domain E-mail Routines  
                   14953: 
                   14954: =over 4
                   14955: 
1.648     raeburn  14956: =item * &build_recipient_list()
1.618     raeburn  14957: 
1.1144    raeburn  14958: Build recipient lists for following types of e-mail:
1.766     raeburn  14959: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14960: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14961: module change checking, student/employee ID conflict checks, as
                   14962: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14963: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14964: 
                   14965: Inputs:
1.619     raeburn  14966: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14967: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14968: requestsmail, updatesmail, or idconflictsmail).
                   14969: 
1.619     raeburn  14970: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14971: 
1.619     raeburn  14972: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  14973: i.e., predates configuration by DC via domainprefs.pm
                   14974: 
                   14975: $requname username of requester (if mailing type is helpdeskmail)
                   14976: 
                   14977: $requdom domain of requester (if mailing type is helpdeskmail)
                   14978: 
                   14979: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14980: 
1.618     raeburn  14981: 
1.655     raeburn  14982: Returns: comma separated list of addresses to which to send e-mail.
                   14983: 
                   14984: =back
1.618     raeburn  14985: 
                   14986: =cut
                   14987: 
                   14988: ############################################################
                   14989: ############################################################
                   14990: sub build_recipient_list {
1.1297    raeburn  14991:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14992:     my @recipients;
1.1270    raeburn  14993:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14994:     my %domconfig =
1.1270    raeburn  14995:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14996:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14997:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14998:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14999:                 my @contacts = ('adminemail','supportemail');
                   15000:                 foreach my $item (@contacts) {
                   15001:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15002:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15003:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15004:                             push(@recipients,$addr);
                   15005:                         }
1.619     raeburn  15006:                     }
1.1270    raeburn  15007:                 }
                   15008:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15009:                 if ($mailing eq 'helpdeskmail') {
                   15010:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15011:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15012:                         my @ok_bccs;
                   15013:                         foreach my $bcc (@bccs) {
                   15014:                             $bcc =~ s/^\s+//g;
                   15015:                             $bcc =~ s/\s+$//g;
                   15016:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15017:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15018:                                     push(@ok_bccs,$bcc);
                   15019:                                 }
                   15020:                             }
                   15021:                         }
                   15022:                         if (@ok_bccs > 0) {
                   15023:                             $allbcc = join(', ',@ok_bccs);
                   15024:                         }
                   15025:                     }
                   15026:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15027:                 }
                   15028:             }
1.766     raeburn  15029:         } elsif ($origmail ne '') {
1.1270    raeburn  15030:             $lastresort = $origmail;
1.618     raeburn  15031:         }
1.1297    raeburn  15032:         if ($mailing eq 'helpdeskmail') {
                   15033:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15034:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15035:                 my ($inststatus,$inststatus_checked);
                   15036:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15037:                     ($env{'user.domain'} ne 'public')) {
                   15038:                     $inststatus_checked = 1;
                   15039:                     $inststatus = $env{'environment.inststatus'};
                   15040:                 }
                   15041:                 unless ($inststatus_checked) {
                   15042:                     if (($requname ne '') && ($requdom ne '')) {
                   15043:                         if (($requname =~ /^$match_username$/) &&
                   15044:                             ($requdom =~ /^$match_domain$/) &&
                   15045:                             (&Apache::lonnet::domain($requdom))) {
                   15046:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15047:                                                                       $requdom);
                   15048:                             unless ($requhome eq 'no_host') {
                   15049:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15050:                                 $inststatus = $userenv{'inststatus'};
                   15051:                                 $inststatus_checked = 1;
                   15052:                             }
                   15053:                         }
                   15054:                     }
                   15055:                 }
                   15056:                 unless ($inststatus_checked) {
                   15057:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15058:                         my %srch = (srchby     => 'email',
                   15059:                                     srchdomain => $defdom,
                   15060:                                     srchterm   => $reqemail,
                   15061:                                     srchtype   => 'exact');
                   15062:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15063:                         foreach my $uname (keys(%srch_results)) {
                   15064:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15065:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15066:                                 $inststatus_checked = 1;
                   15067:                                 last;
                   15068:                             }
                   15069:                         }
                   15070:                         unless ($inststatus_checked) {
                   15071:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15072:                             if ($dirsrchres eq 'ok') {
                   15073:                                 foreach my $uname (keys(%srch_results)) {
                   15074:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15075:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15076:                                         $inststatus_checked = 1;
                   15077:                                         last;
                   15078:                                     }
                   15079:                                 }
                   15080:                             }
                   15081:                         }
                   15082:                     }
                   15083:                 }
                   15084:                 if ($inststatus ne '') {
                   15085:                     foreach my $status (split(/\:/,$inststatus)) {
                   15086:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15087:                             my @contacts = ('adminemail','supportemail');
                   15088:                             foreach my $item (@contacts) {
                   15089:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15090:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15091:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15092:                                         push(@recipients,$addr);
                   15093:                                     }
                   15094:                                 }
                   15095:                             }
                   15096:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15097:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15098:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15099:                                 my @ok_bccs;
                   15100:                                 foreach my $bcc (@bccs) {
                   15101:                                     $bcc =~ s/^\s+//g;
                   15102:                                     $bcc =~ s/\s+$//g;
                   15103:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15104:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15105:                                             push(@ok_bccs,$bcc);
                   15106:                                         }
                   15107:                                     }
                   15108:                                 }
                   15109:                                 if (@ok_bccs > 0) {
                   15110:                                     $allbcc = join(', ',@ok_bccs);
                   15111:                                 }
                   15112:                             }
                   15113:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15114:                             last;
                   15115:                         }
                   15116:                     }
                   15117:                 }
                   15118:             }
                   15119:         }
1.619     raeburn  15120:     } elsif ($origmail ne '') {
1.1270    raeburn  15121:         $lastresort = $origmail;
                   15122:     }
1.1297    raeburn  15123:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15124:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15125:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15126:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15127:             my %what = (
                   15128:                           perlvar => 1,
                   15129:                        );
                   15130:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15131:             if ($primary) {
                   15132:                 my $gotaddr;
                   15133:                 my ($result,$returnhash) =
                   15134:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15135:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15136:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15137:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15138:                         $gotaddr = 1;
                   15139:                     }
                   15140:                 }
                   15141:                 unless ($gotaddr) {
                   15142:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15143:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15144:                     unless ($uintdom eq $intdom) {
                   15145:                         my %domconfig =
                   15146:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15147:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15148:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15149:                                 my @contacts = ('adminemail','supportemail');
                   15150:                                 foreach my $item (@contacts) {
                   15151:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15152:                                         my $addr = $domconfig{'contacts'}{$item};
                   15153:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15154:                                             push(@recipients,$addr);
                   15155:                                         }
                   15156:                                     }
                   15157:                                 }
                   15158:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15159:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15160:                                 }
                   15161:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15162:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15163:                                     my @ok_bccs;
                   15164:                                     foreach my $bcc (@bccs) {
                   15165:                                         $bcc =~ s/^\s+//g;
                   15166:                                         $bcc =~ s/\s+$//g;
                   15167:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15168:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15169:                                                 push(@ok_bccs,$bcc);
                   15170:                                             }
                   15171:                                         }
                   15172:                                     }
                   15173:                                     if (@ok_bccs > 0) {
                   15174:                                         $allbcc = join(', ',@ok_bccs);
                   15175:                                     }
                   15176:                                 }
                   15177:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15178:                             }
                   15179:                         }
                   15180:                     }
                   15181:                 }
                   15182:             }
                   15183:         }
1.618     raeburn  15184:     }
1.688     raeburn  15185:     if (defined($defmail)) {
                   15186:         if ($defmail ne '') {
                   15187:             push(@recipients,$defmail);
                   15188:         }
1.618     raeburn  15189:     }
                   15190:     if ($otheremails) {
1.619     raeburn  15191:         my @others;
                   15192:         if ($otheremails =~ /,/) {
                   15193:             @others = split(/,/,$otheremails);
1.618     raeburn  15194:         } else {
1.619     raeburn  15195:             push(@others,$otheremails);
                   15196:         }
                   15197:         foreach my $addr (@others) {
                   15198:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15199:                 push(@recipients,$addr);
                   15200:             }
1.618     raeburn  15201:         }
                   15202:     }
1.1298    raeburn  15203:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15204:         if ((!@recipients) && ($lastresort ne '')) {
                   15205:             push(@recipients,$lastresort);
                   15206:         }
                   15207:     } elsif ($lastresort ne '') {
                   15208:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15209:             push(@recipients,$lastresort);
                   15210:         }
                   15211:     }
1.1271    raeburn  15212:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15213:     if (wantarray) {
                   15214:         return ($recipientlist,$allbcc,$addtext);
                   15215:     } else {
                   15216:         return $recipientlist;
                   15217:     }
1.618     raeburn  15218: }
                   15219: 
1.127     matthew  15220: ############################################################
                   15221: ############################################################
1.154     albertel 15222: 
1.655     raeburn  15223: =pod
                   15224: 
1.1224    musolffc 15225: =over 4
                   15226: 
1.1223    musolffc 15227: =item * &mime_email()
                   15228: 
                   15229: Sends an email with a possible attachment
                   15230: 
                   15231: Inputs:
                   15232: 
                   15233: =over 4
                   15234: 
                   15235: from -              Sender's email address
                   15236: 
1.1343    raeburn  15237: replyto -           Reply-To email address
                   15238: 
1.1223    musolffc 15239: to -                Email address of recipient
                   15240: 
                   15241: subject -           Subject of email
                   15242: 
                   15243: body -              Body of email
                   15244: 
                   15245: cc_string -         Carbon copy email address
                   15246: 
                   15247: bcc -               Blind carbon copy email address
                   15248: 
                   15249: attachment_path -   Path of file to be attached
                   15250: 
                   15251: file_name -         Name of file to be attached
                   15252: 
                   15253: attachment_text -   The body of an attachment of type "TEXT"
                   15254: 
                   15255: =back
                   15256: 
                   15257: =back
                   15258: 
                   15259: =cut
                   15260: 
                   15261: ############################################################
                   15262: ############################################################
                   15263: 
                   15264: sub mime_email {
1.1343    raeburn  15265:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15266:         $file_name,$attachment_text) = @_;
                   15267:  
1.1223    musolffc 15268:     my $msg = MIME::Lite->new(
                   15269:              From    => $from,
                   15270:              To      => $to,
                   15271:              Subject => $subject,
                   15272:              Type    =>'TEXT',
                   15273:              Data    => $body,
                   15274:              );
1.1343    raeburn  15275:     if ($replyto ne '') {
                   15276:         $msg->add("Reply-To" => $replyto);
                   15277:     }
1.1223    musolffc 15278:     if ($cc_string ne '') {
                   15279:         $msg->add("Cc" => $cc_string);
                   15280:     }
                   15281:     if ($bcc ne '') {
                   15282:         $msg->add("Bcc" => $bcc);
                   15283:     }
                   15284:     $msg->attr("content-type"         => "text/plain");
                   15285:     $msg->attr("content-type.charset" => "UTF-8");
                   15286:     # Attach file if given
                   15287:     if ($attachment_path) {
                   15288:         unless ($file_name) {
                   15289:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15290:         }
                   15291:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15292:         $msg->attach(Type     => $type,
                   15293:                      Path     => $attachment_path,
                   15294:                      Filename => $file_name
                   15295:                      );
                   15296:     # Otherwise attach text if given
                   15297:     } elsif ($attachment_text) {
                   15298:         $msg->attach(Type => 'TEXT',
                   15299:                      Data => $attachment_text);
                   15300:     }
                   15301:     # Send it
                   15302:     $msg->send('sendmail');
                   15303: }
                   15304: 
                   15305: ############################################################
                   15306: ############################################################
                   15307: 
                   15308: =pod
                   15309: 
1.655     raeburn  15310: =head1 Course Catalog Routines
                   15311: 
                   15312: =over 4
                   15313: 
                   15314: =item * &gather_categories()
                   15315: 
                   15316: Converts category definitions - keys of categories hash stored in  
                   15317: coursecategories in configuration.db on the primary library server in a 
                   15318: domain - to an array.  Also generates javascript and idx hash used to 
                   15319: generate Domain Coordinator interface for editing Course Categories.
                   15320: 
                   15321: Inputs:
1.663     raeburn  15322: 
1.655     raeburn  15323: categories (reference to hash of category definitions).
1.663     raeburn  15324: 
1.655     raeburn  15325: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15326:       categories and subcategories).
1.663     raeburn  15327: 
1.655     raeburn  15328: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15329:       editing Course Categories).
1.663     raeburn  15330: 
1.655     raeburn  15331: jsarray (reference to array of categories used to create Javascript arrays for
                   15332:          Domain Coordinator interface for editing Course Categories).
                   15333: 
                   15334: Returns: nothing
                   15335: 
                   15336: Side effects: populates cats, idx and jsarray. 
                   15337: 
                   15338: =cut
                   15339: 
                   15340: sub gather_categories {
                   15341:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15342:     my %counters;
                   15343:     my $num = 0;
                   15344:     foreach my $item (keys(%{$categories})) {
                   15345:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15346:         if ($container eq '' && $depth == 0) {
                   15347:             $cats->[$depth][$categories->{$item}] = $cat;
                   15348:         } else {
                   15349:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15350:         }
                   15351:         my ($escitem,$tail) = split(/:/,$item,2);
                   15352:         if ($counters{$tail} eq '') {
                   15353:             $counters{$tail} = $num;
                   15354:             $num ++;
                   15355:         }
                   15356:         if (ref($idx) eq 'HASH') {
                   15357:             $idx->{$item} = $counters{$tail};
                   15358:         }
                   15359:         if (ref($jsarray) eq 'ARRAY') {
                   15360:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15361:         }
                   15362:     }
                   15363:     return;
                   15364: }
                   15365: 
                   15366: =pod
                   15367: 
                   15368: =item * &extract_categories()
                   15369: 
                   15370: Used to generate breadcrumb trails for course categories.
                   15371: 
                   15372: Inputs:
1.663     raeburn  15373: 
1.655     raeburn  15374: categories (reference to hash of category definitions).
1.663     raeburn  15375: 
1.655     raeburn  15376: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15377:       categories and subcategories).
1.663     raeburn  15378: 
1.655     raeburn  15379: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15380: 
1.655     raeburn  15381: allitems (reference to hash - key is category key 
                   15382:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15383: 
1.655     raeburn  15384: idx (reference to hash of counters used in Domain Coordinator interface for
                   15385:       editing Course Categories).
1.663     raeburn  15386: 
1.655     raeburn  15387: jsarray (reference to array of categories used to create Javascript arrays for
                   15388:          Domain Coordinator interface for editing Course Categories).
                   15389: 
1.665     raeburn  15390: subcats (reference to hash of arrays containing all subcategories within each 
                   15391:          category, -recursive)
                   15392: 
1.1321    raeburn  15393: maxd (reference to hash used to hold max depth for all top-level categories).
                   15394: 
1.655     raeburn  15395: Returns: nothing
                   15396: 
                   15397: Side effects: populates trails and allitems hash references.
                   15398: 
                   15399: =cut
                   15400: 
                   15401: sub extract_categories {
1.1321    raeburn  15402:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15403:     if (ref($categories) eq 'HASH') {
                   15404:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15405:         if (ref($cats->[0]) eq 'ARRAY') {
                   15406:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15407:                 my $name = $cats->[0][$i];
                   15408:                 my $item = &escape($name).'::0';
                   15409:                 my $trailstr;
                   15410:                 if ($name eq 'instcode') {
                   15411:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15412:                 } elsif ($name eq 'communities') {
                   15413:                     $trailstr = &mt('Communities');
1.1239    raeburn  15414:                 } elsif ($name eq 'placement') {
                   15415:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15416:                 } else {
                   15417:                     $trailstr = $name;
                   15418:                 }
                   15419:                 if ($allitems->{$item} eq '') {
                   15420:                     push(@{$trails},$trailstr);
                   15421:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15422:                 }
                   15423:                 my @parents = ($name);
                   15424:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15425:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15426:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15427:                         if (ref($subcats) eq 'HASH') {
                   15428:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15429:                         }
1.1321    raeburn  15430:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15431:                     }
                   15432:                 } else {
                   15433:                     if (ref($subcats) eq 'HASH') {
                   15434:                         $subcats->{$item} = [];
1.655     raeburn  15435:                     }
1.1321    raeburn  15436:                     if (ref($maxd) eq 'HASH') {
                   15437:                         $maxd->{$name} = 1;
                   15438:                     }
1.655     raeburn  15439:                 }
                   15440:             }
                   15441:         }
                   15442:     }
                   15443:     return;
                   15444: }
                   15445: 
                   15446: =pod
                   15447: 
1.1162    raeburn  15448: =item * &recurse_categories()
1.655     raeburn  15449: 
                   15450: Recursively used to generate breadcrumb trails for course categories.
                   15451: 
                   15452: Inputs:
1.663     raeburn  15453: 
1.655     raeburn  15454: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15455:       categories and subcategories).
1.663     raeburn  15456: 
1.655     raeburn  15457: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15458: 
                   15459: category (current course category, for which breadcrumb trail is being generated).
                   15460: 
                   15461: trails (reference to array of breadcrumb trails for each category).
                   15462: 
1.655     raeburn  15463: allitems (reference to hash - key is category key
                   15464:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15465: 
1.655     raeburn  15466: parents (array containing containers directories for current category, 
                   15467:          back to top level). 
                   15468: 
                   15469: Returns: nothing
                   15470: 
                   15471: Side effects: populates trails and allitems hash references
                   15472: 
                   15473: =cut
                   15474: 
                   15475: sub recurse_categories {
1.1321    raeburn  15476:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15477:     my $shallower = $depth - 1;
                   15478:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15479:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15480:             my $name = $cats->[$depth]{$category}[$k];
                   15481:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15482:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15483:             if ($allitems->{$item} eq '') {
                   15484:                 push(@{$trails},$trailstr);
                   15485:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15486:             }
                   15487:             my $deeper = $depth+1;
                   15488:             push(@{$parents},$category);
1.665     raeburn  15489:             if (ref($subcats) eq 'HASH') {
                   15490:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15491:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15492:                     my $higher;
                   15493:                     if ($j > 0) {
                   15494:                         $higher = &escape($parents->[$j]).':'.
                   15495:                                   &escape($parents->[$j-1]).':'.$j;
                   15496:                     } else {
                   15497:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15498:                     }
                   15499:                     push(@{$subcats->{$higher}},$subcat);
                   15500:                 }
                   15501:             }
                   15502:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  15503:                                 $subcats,$maxd);
1.655     raeburn  15504:             pop(@{$parents});
                   15505:         }
                   15506:     } else {
                   15507:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15508:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15509:         if ($allitems->{$item} eq '') {
                   15510:             push(@{$trails},$trailstr);
                   15511:             $allitems->{$item} = scalar(@{$trails})-1;
                   15512:         }
1.1321    raeburn  15513:         if (ref($maxd) eq 'HASH') {
                   15514:             if ($depth > $maxd->{$parents->[0]}) {
                   15515:                 $maxd->{$parents->[0]} = $depth;
                   15516:             }
                   15517:         }
1.655     raeburn  15518:     }
                   15519:     return;
                   15520: }
                   15521: 
1.663     raeburn  15522: =pod
                   15523: 
1.1162    raeburn  15524: =item * &assign_categories_table()
1.663     raeburn  15525: 
                   15526: Create a datatable for display of hierarchical categories in a domain,
                   15527: with checkboxes to allow a course to be categorized. 
                   15528: 
                   15529: Inputs:
                   15530: 
                   15531: cathash - reference to hash of categories defined for the domain (from
                   15532:           configuration.db)
                   15533: 
                   15534: currcat - scalar with an & separated list of categories assigned to a course. 
                   15535: 
1.919     raeburn  15536: type    - scalar contains course type (Course or Community).
                   15537: 
1.1260    raeburn  15538: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15539:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15540: 
1.663     raeburn  15541: Returns: $output (markup to be displayed) 
                   15542: 
                   15543: =cut
                   15544: 
                   15545: sub assign_categories_table {
1.1259    raeburn  15546:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15547:     my $output;
                   15548:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  15549:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15550:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15551:         $maxdepth = scalar(@cats);
                   15552:         if (@cats > 0) {
                   15553:             my $itemcount = 0;
                   15554:             if (ref($cats[0]) eq 'ARRAY') {
                   15555:                 my @currcategories;
                   15556:                 if ($currcat ne '') {
                   15557:                     @currcategories = split('&',$currcat);
                   15558:                 }
1.919     raeburn  15559:                 my $table;
1.663     raeburn  15560:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15561:                     my $parent = $cats[0][$i];
1.919     raeburn  15562:                     next if ($parent eq 'instcode');
                   15563:                     if ($type eq 'Community') {
                   15564:                         next unless ($parent eq 'communities');
1.1239    raeburn  15565:                     } elsif ($type eq 'Placement') {
                   15566:                         next unless ($parent eq 'placement');
1.919     raeburn  15567:                     } else {
1.1239    raeburn  15568:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15569:                     }
1.663     raeburn  15570:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15571:                     my $item = &escape($parent).'::0';
                   15572:                     my $checked = '';
                   15573:                     if (@currcategories > 0) {
                   15574:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15575:                             $checked = ' checked="checked"';
1.663     raeburn  15576:                         }
                   15577:                     }
1.919     raeburn  15578:                     my $parent_title = $parent;
                   15579:                     if ($parent eq 'communities') {
                   15580:                         $parent_title = &mt('Communities');
1.1239    raeburn  15581:                     } elsif ($parent eq 'placement') {
                   15582:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15583:                     }
                   15584:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15585:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15586:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15587:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15588:                     my $depth = 1;
                   15589:                     push(@path,$parent);
1.1259    raeburn  15590:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15591:                     pop(@path);
1.919     raeburn  15592:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15593:                     $itemcount ++;
                   15594:                 }
1.919     raeburn  15595:                 if ($itemcount) {
                   15596:                     $output = &Apache::loncommon::start_data_table().
                   15597:                               $table.
                   15598:                               &Apache::loncommon::end_data_table();
                   15599:                 }
1.663     raeburn  15600:             }
                   15601:         }
                   15602:     }
                   15603:     return $output;
                   15604: }
                   15605: 
                   15606: =pod
                   15607: 
1.1162    raeburn  15608: =item * &assign_category_rows()
1.663     raeburn  15609: 
                   15610: Create a datatable row for display of nested categories in a domain,
                   15611: with checkboxes to allow a course to be categorized,called recursively.
                   15612: 
                   15613: Inputs:
                   15614: 
                   15615: itemcount - track row number for alternating colors
                   15616: 
                   15617: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15618:       categories and subcategories.
                   15619: 
                   15620: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15621: 
                   15622: parent - parent of current category item
                   15623: 
                   15624: path - Array containing all categories back up through the hierarchy from the
                   15625:        current category to the top level.
                   15626: 
                   15627: currcategories - reference to array of current categories assigned to the course
                   15628: 
1.1260    raeburn  15629: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15630:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15631: 
1.663     raeburn  15632: Returns: $output (markup to be displayed).
                   15633: 
                   15634: =cut
                   15635: 
                   15636: sub assign_category_rows {
1.1259    raeburn  15637:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15638:     my ($text,$name,$item,$chgstr);
                   15639:     if (ref($cats) eq 'ARRAY') {
                   15640:         my $maxdepth = scalar(@{$cats});
                   15641:         if (ref($cats->[$depth]) eq 'HASH') {
                   15642:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15643:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15644:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15645:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15646:                 for (my $j=0; $j<$numchildren; $j++) {
                   15647:                     $name = $cats->[$depth]{$parent}[$j];
                   15648:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15649:                     my $deeper = $depth+1;
                   15650:                     my $checked = '';
                   15651:                     if (ref($currcategories) eq 'ARRAY') {
                   15652:                         if (@{$currcategories} > 0) {
                   15653:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15654:                                 $checked = ' checked="checked"';
1.663     raeburn  15655:                             }
                   15656:                         }
                   15657:                     }
1.664     raeburn  15658:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15659:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15660:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15661:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15662:                              '</td><td>';
1.663     raeburn  15663:                     if (ref($path) eq 'ARRAY') {
                   15664:                         push(@{$path},$name);
1.1259    raeburn  15665:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15666:                         pop(@{$path});
                   15667:                     }
                   15668:                     $text .= '</td></tr>';
                   15669:                 }
                   15670:                 $text .= '</table></td>';
                   15671:             }
                   15672:         }
                   15673:     }
                   15674:     return $text;
                   15675: }
                   15676: 
1.1181    raeburn  15677: =pod
                   15678: 
                   15679: =back
                   15680: 
                   15681: =cut
                   15682: 
1.655     raeburn  15683: ############################################################
                   15684: ############################################################
                   15685: 
                   15686: 
1.443     albertel 15687: sub commit_customrole {
1.664     raeburn  15688:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15689:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15690:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15691:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15692:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15693:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15694:                  '</b><br />';
                   15695:     return $output;
                   15696: }
                   15697: 
                   15698: sub commit_standardrole {
1.1116    raeburn  15699:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15700:     my ($output,$logmsg,$linefeed);
                   15701:     if ($context eq 'auto') {
                   15702:         $linefeed = "\n";
                   15703:     } else {
                   15704:         $linefeed = "<br />\n";
                   15705:     }  
1.443     albertel 15706:     if ($three eq 'st') {
1.541     raeburn  15707:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15708:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15709:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15710:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15711:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15712:         } else {
1.541     raeburn  15713:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15714:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15715:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15716:             if ($context eq 'auto') {
                   15717:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15718:             } else {
                   15719:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15720:                &mt('Add to classlist').': <b>ok</b>';
                   15721:             }
                   15722:             $output .= $linefeed;
1.443     albertel 15723:         }
                   15724:     } else {
                   15725:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15726:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15727:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15728:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15729:         if ($context eq 'auto') {
                   15730:             $output .= $result.$linefeed;
                   15731:         } else {
                   15732:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15733:         }
1.443     albertel 15734:     }
                   15735:     return $output;
                   15736: }
                   15737: 
                   15738: sub commit_studentrole {
1.1116    raeburn  15739:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15740:         $credits) = @_;
1.626     raeburn  15741:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15742:     if ($context eq 'auto') {
                   15743:         $linefeed = "\n";
                   15744:     } else {
                   15745:         $linefeed = '<br />'."\n";
                   15746:     }
1.443     albertel 15747:     if (defined($one) && defined($two)) {
                   15748:         my $cid=$one.'_'.$two;
                   15749:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15750:         my $secchange = 0;
                   15751:         my $expire_role_result;
                   15752:         my $modify_section_result;
1.628     raeburn  15753:         if ($oldsec ne '-1') { 
                   15754:             if ($oldsec ne $sec) {
1.443     albertel 15755:                 $secchange = 1;
1.628     raeburn  15756:                 my $now = time;
1.443     albertel 15757:                 my $uurl='/'.$cid;
                   15758:                 $uurl=~s/\_/\//g;
                   15759:                 if ($oldsec) {
                   15760:                     $uurl.='/'.$oldsec;
                   15761:                 }
1.626     raeburn  15762:                 $oldsecurl = $uurl;
1.628     raeburn  15763:                 $expire_role_result = 
1.652     raeburn  15764:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15765:                 if ($env{'request.course.sec'} ne '') { 
                   15766:                     if ($expire_role_result eq 'refused') {
                   15767:                         my @roles = ('st');
                   15768:                         my @statuses = ('previous');
                   15769:                         my @roledoms = ($one);
                   15770:                         my $withsec = 1;
                   15771:                         my %roleshash = 
                   15772:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15773:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15774:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15775:                             my ($oldstart,$oldend) = 
                   15776:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15777:                             if ($oldend > 0 && $oldend <= $now) {
                   15778:                                 $expire_role_result = 'ok';
                   15779:                             }
                   15780:                         }
                   15781:                     }
                   15782:                 }
1.443     albertel 15783:                 $result = $expire_role_result;
                   15784:             }
                   15785:         }
                   15786:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15787:             $modify_section_result = 
                   15788:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15789:                                                            undef,undef,undef,$sec,
                   15790:                                                            $end,$start,'','',$cid,
                   15791:                                                            '',$context,$credits);
1.443     albertel 15792:             if ($modify_section_result =~ /^ok/) {
                   15793:                 if ($secchange == 1) {
1.628     raeburn  15794:                     if ($sec eq '') {
                   15795:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15796:                     } else {
                   15797:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15798:                     }
1.443     albertel 15799:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15800:                     if ($sec eq '') {
                   15801:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15802:                     } else {
                   15803:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15804:                     }
1.443     albertel 15805:                 } else {
1.628     raeburn  15806:                     if ($sec eq '') {
                   15807:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15808:                     } else {
                   15809:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15810:                     }
1.443     albertel 15811:                 }
                   15812:             } else {
1.1115    raeburn  15813:                 if ($secchange) { 
1.628     raeburn  15814:                     $$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;
                   15815:                 } else {
                   15816:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15817:                 }
1.443     albertel 15818:             }
                   15819:             $result = $modify_section_result;
                   15820:         } elsif ($secchange == 1) {
1.628     raeburn  15821:             if ($oldsec eq '') {
1.1103    raeburn  15822:                 $$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  15823:             } else {
                   15824:                 $$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;
                   15825:             }
1.626     raeburn  15826:             if ($expire_role_result eq 'refused') {
                   15827:                 my $newsecurl = '/'.$cid;
                   15828:                 $newsecurl =~ s/\_/\//g;
                   15829:                 if ($sec ne '') {
                   15830:                     $newsecurl.='/'.$sec;
                   15831:                 }
                   15832:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15833:                     if ($sec eq '') {
                   15834:                         $$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;
                   15835:                     } else {
                   15836:                         $$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;
                   15837:                     }
                   15838:                 }
                   15839:             }
1.443     albertel 15840:         }
                   15841:     } else {
1.626     raeburn  15842:         $$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 15843:         $result = "error: incomplete course id\n";
                   15844:     }
                   15845:     return $result;
                   15846: }
                   15847: 
1.1108    raeburn  15848: sub show_role_extent {
                   15849:     my ($scope,$context,$role) = @_;
                   15850:     $scope =~ s{^/}{};
                   15851:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15852:     push(@courseroles,'co');
                   15853:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15854:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15855:         $scope =~ s{/}{_};
                   15856:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15857:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15858:         my ($audom,$auname) = split(/\//,$scope);
                   15859:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15860:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15861:     } else {
                   15862:         $scope =~ s{/$}{};
                   15863:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15864:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15865:     }
                   15866: }
                   15867: 
1.443     albertel 15868: ############################################################
                   15869: ############################################################
                   15870: 
1.566     albertel 15871: sub check_clone {
1.578     raeburn  15872:     my ($args,$linefeed) = @_;
1.566     albertel 15873:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15874:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15875:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  15876:     my $clonetitle;
                   15877:     my @clonemsg;
1.566     albertel 15878:     my $can_clone = 0;
1.944     raeburn  15879:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15880:     if ($lctype ne 'community') {
                   15881:         $lctype = 'course';
                   15882:     }
1.566     albertel 15883:     if ($clonehome eq 'no_host') {
1.944     raeburn  15884:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  15885:             push(@clonemsg,({
                   15886:                               mt => 'No new community created.',
                   15887:                               args => [],
                   15888:                             },
                   15889:                             {
                   15890:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   15891:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   15892:                             }));
1.908     raeburn  15893:         } else {
1.1344    raeburn  15894:             push(@clonemsg,({
                   15895:                               mt => 'No new course created.',
                   15896:                               args => [],
                   15897:                             },
                   15898:                             {
                   15899:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   15900:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15901:                             }));
                   15902:         }
1.566     albertel 15903:     } else {
                   15904: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  15905:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  15906:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15907:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  15908:                 push(@clonemsg,({
                   15909:                                   mt => 'No new community created.',
                   15910:                                   args => [],
                   15911:                                 },
                   15912:                                 {
                   15913:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   15914:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15915:                                 }));
                   15916:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  15917:             }
                   15918:         }
1.1262    raeburn  15919: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15920:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15921: 	    $can_clone = 1;
                   15922: 	} else {
1.1221    raeburn  15923: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15924: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15925:             if ($clonehash{'cloners'} eq '') {
                   15926:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15927:                 if ($domdefs{'canclone'}) {
                   15928:                     unless ($domdefs{'canclone'} eq 'none') {
                   15929:                         if ($domdefs{'canclone'} eq 'domain') {
                   15930:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15931:                                 $can_clone = 1;
                   15932:                             }
                   15933:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15934:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15935:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15936:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15937:                                 $can_clone = 1;
                   15938:                             }
                   15939:                         }
                   15940:                     }
                   15941:                 }
1.578     raeburn  15942:             } else {
1.1221    raeburn  15943: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15944:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15945:                     $can_clone = 1;
1.1221    raeburn  15946:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15947:                     $can_clone = 1;
1.1225    raeburn  15948:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15949:                     $can_clone = 1;
1.1221    raeburn  15950:                 }
                   15951:                 unless ($can_clone) {
1.1225    raeburn  15952:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15953:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15954:                         my (%gotdomdefaults,%gotcodedefaults);
                   15955:                         foreach my $cloner (@cloners) {
                   15956:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15957:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15958:                                 my (%codedefaults,@code_order);
                   15959:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15960:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15961:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15962:                                     }
                   15963:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15964:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15965:                                     }
                   15966:                                 } else {
                   15967:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15968:                                                                             \%codedefaults,
                   15969:                                                                             \@code_order);
                   15970:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15971:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15972:                                 }
                   15973:                                 if (@code_order > 0) {
                   15974:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15975:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15976:                                                                                 $args->{'crscode'})) {
                   15977:                                         $can_clone = 1;
                   15978:                                         last;
                   15979:                                     }
                   15980:                                 }
                   15981:                             }
                   15982:                         }
                   15983:                     }
1.1225    raeburn  15984:                 }
                   15985:             }
                   15986:             unless ($can_clone) {
                   15987:                 my $ccrole = 'cc';
                   15988:                 if ($args->{'crstype'} eq 'Community') {
                   15989:                     $ccrole = 'co';
                   15990:                 }
                   15991: 	        my %roleshash =
                   15992: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15993: 					          $args->{'ccdomain'},
                   15994:                                                   'userroles',['active'],[$ccrole],
                   15995: 					          [$args->{'clonedomain'}]);
                   15996: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15997:                     $can_clone = 1;
                   15998:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15999:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16000:                     $can_clone = 1;
1.1221    raeburn  16001:                 }
                   16002:             }
                   16003:             unless ($can_clone) {
                   16004:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16005:                     push(@clonemsg,({
                   16006:                                       mt => 'No new community created.',
                   16007:                                       args => [],
                   16008:                                     },
                   16009:                                     {
                   16010:                                       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]).',
                   16011:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16012:                                     }));
1.942     raeburn  16013:                 } else {
1.1344    raeburn  16014:                     push(@clonemsg,({
                   16015:                                       mt => 'No new course created.',
                   16016:                                       args => [],
                   16017:                                     },
                   16018:                                     {
                   16019:                                       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]).',
                   16020:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16021:                                     }));
1.1221    raeburn  16022:                 }
1.566     albertel 16023: 	    }
1.578     raeburn  16024:         }
1.566     albertel 16025:     }
1.1344    raeburn  16026:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16027: }
                   16028: 
1.444     albertel 16029: sub construct_course {
1.1262    raeburn  16030:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16031:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16032:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16033:     my $linefeed =  '<br />'."\n";
                   16034:     if ($context eq 'auto') {
                   16035:         $linefeed = "\n";
                   16036:     }
1.566     albertel 16037: 
                   16038: #
                   16039: # Are we cloning?
                   16040: #
1.1344    raeburn  16041:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16042:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16043: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16044:         if (!$can_clone) {
1.1344    raeburn  16045: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16046: 	}
                   16047:     }
                   16048: 
1.444     albertel 16049: #
                   16050: # Open course
                   16051: #
1.1239    raeburn  16052:     my $showncrstype;
                   16053:     if ($args->{'crstype'} eq 'Placement') {
                   16054:         $showncrstype = 'placement test'; 
                   16055:     } else {  
                   16056:         $showncrstype = lc($args->{'crstype'});
                   16057:     }
1.444     albertel 16058:     my %cenv=();
                   16059:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16060:                                              $args->{'cdescr'},
                   16061:                                              $args->{'curl'},
                   16062:                                              $args->{'course_home'},
                   16063:                                              $args->{'nonstandard'},
                   16064:                                              $args->{'crscode'},
                   16065:                                              $args->{'ccuname'}.':'.
                   16066:                                              $args->{'ccdomain'},
1.882     raeburn  16067:                                              $args->{'crstype'},
1.1344    raeburn  16068:                                              $cnum,$context,$category,
                   16069:                                              $callercontext);
1.444     albertel 16070: 
                   16071:     # Note: The testing routines depend on this being output; see 
                   16072:     # Utils::Course. This needs to at least be output as a comment
                   16073:     # if anyone ever decides to not show this, and Utils::Course::new
                   16074:     # will need to be suitably modified.
1.1344    raeburn  16075:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16076:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16077:     } else {
                   16078:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16079:     }
1.943     raeburn  16080:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16081:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16082:     }
                   16083: 
1.444     albertel 16084: #
                   16085: # Check if created correctly
                   16086: #
1.479     albertel 16087:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16088:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16089:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16090:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16091:             $outcome .= &mt_user($user_lh,
                   16092:                             'Course creation failed, unrecognized course home server.');
                   16093:         } else {
                   16094:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16095:         }
                   16096:         $outcome .= $linefeed;
                   16097:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16098:     }
1.541     raeburn  16099:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16100: 
1.444     albertel 16101: #
1.566     albertel 16102: # Do the cloning
                   16103: #   
1.1344    raeburn  16104:     my @clonemsg;
1.566     albertel 16105:     if ($can_clone && $cloneid) {
1.1344    raeburn  16106:         push(@clonemsg,
                   16107:                       {
                   16108:                           mt => 'Created [_1] by cloning from [_2]',
                   16109:                           args => [$showncrstype,$clonetitle],
                   16110:                       });
1.566     albertel 16111: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16112: # Copy all files
1.1344    raeburn  16113:         my @info =
                   16114: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16115: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16116:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16117:                                                      $args->{'tinyurls'});
                   16118:         if (@info) {
                   16119:             push(@clonemsg,@info);
                   16120:         }
1.444     albertel 16121: # Restore URL
1.566     albertel 16122: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16123: # Restore title
1.566     albertel 16124: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16125: # Restore creation date, creator and creation context.
                   16126:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16127:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16128:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16129: # Mark as cloned
1.566     albertel 16130: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16131: # Need to clone grading mode
                   16132:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16133:         $cenv{'grading'}=$newenv{'grading'};
                   16134: # Do not clone these environment entries
                   16135:         &Apache::lonnet::del('environment',
                   16136:                   ['default_enrollment_start_date',
                   16137:                    'default_enrollment_end_date',
                   16138:                    'question.email',
                   16139:                    'policy.email',
                   16140:                    'comment.email',
                   16141:                    'pch.users.denied',
1.725     raeburn  16142:                    'plc.users.denied',
                   16143:                    'hidefromcat',
1.1121    raeburn  16144:                    'checkforpriv',
1.1166    raeburn  16145:                    'categories',
                   16146:                    'internal.uniquecode'],
1.638     www      16147:                    $$crsudom,$$crsunum);
1.1170    raeburn  16148:         if ($args->{'textbook'}) {
                   16149:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16150:         }
1.444     albertel 16151:     }
1.566     albertel 16152: 
1.444     albertel 16153: #
                   16154: # Set environment (will override cloned, if existing)
                   16155: #
                   16156:     my @sections = ();
                   16157:     my @xlists = ();
                   16158:     if ($args->{'crstype'}) {
                   16159:         $cenv{'type'}=$args->{'crstype'};
                   16160:     }
                   16161:     if ($args->{'crsid'}) {
                   16162:         $cenv{'courseid'}=$args->{'crsid'};
                   16163:     }
                   16164:     if ($args->{'crscode'}) {
                   16165:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16166:     }
                   16167:     if ($args->{'crsquota'} ne '') {
                   16168:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16169:     } else {
                   16170:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16171:     }
                   16172:     if ($args->{'ccuname'}) {
                   16173:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16174:                                         ':'.$args->{'ccdomain'};
                   16175:     } else {
                   16176:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16177:     }
1.1116    raeburn  16178:     if ($args->{'defaultcredits'}) {
                   16179:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16180:     }
1.444     albertel 16181:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16182:     if ($args->{'crssections'}) {
                   16183:         $cenv{'internal.sectionnums'} = '';
                   16184:         if ($args->{'crssections'} =~ m/,/) {
                   16185:             @sections = split/,/,$args->{'crssections'};
                   16186:         } else {
                   16187:             $sections[0] = $args->{'crssections'};
                   16188:         }
                   16189:         if (@sections > 0) {
                   16190:             foreach my $item (@sections) {
                   16191:                 my ($sec,$gp) = split/:/,$item;
                   16192:                 my $class = $args->{'crscode'}.$sec;
                   16193:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16194:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16195:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16196:                     push(@badclasses,$class);
1.444     albertel 16197:                 }
                   16198:             }
                   16199:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16200:         }
                   16201:     }
                   16202: # do not hide course coordinator from staff listing, 
                   16203: # even if privileged
                   16204:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16205: # add course coordinator's domain to domains to check for privileged users
                   16206: # if different to course domain
                   16207:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16208:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16209:     }
1.444     albertel 16210: # add crosslistings
                   16211:     if ($args->{'crsxlist'}) {
                   16212:         $cenv{'internal.crosslistings'}='';
                   16213:         if ($args->{'crsxlist'} =~ m/,/) {
                   16214:             @xlists = split/,/,$args->{'crsxlist'};
                   16215:         } else {
                   16216:             $xlists[0] = $args->{'crsxlist'};
                   16217:         }
                   16218:         if (@xlists > 0) {
                   16219:             foreach my $item (@xlists) {
                   16220:                 my ($xl,$gp) = split/:/,$item;
                   16221:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16222:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16223:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16224:                     push(@badclasses,$xl);
1.444     albertel 16225:                 }
                   16226:             }
                   16227:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16228:         }
                   16229:     }
                   16230:     if ($args->{'autoadds'}) {
                   16231:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16232:     }
                   16233:     if ($args->{'autodrops'}) {
                   16234:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16235:     }
                   16236: # check for notification of enrollment changes
                   16237:     my @notified = ();
                   16238:     if ($args->{'notify_owner'}) {
                   16239:         if ($args->{'ccuname'} ne '') {
                   16240:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16241:         }
                   16242:     }
                   16243:     if ($args->{'notify_dc'}) {
                   16244:         if ($uname ne '') { 
1.630     raeburn  16245:             push(@notified,$uname.':'.$udom);
1.444     albertel 16246:         }
                   16247:     }
                   16248:     if (@notified > 0) {
                   16249:         my $notifylist;
                   16250:         if (@notified > 1) {
                   16251:             $notifylist = join(',',@notified);
                   16252:         } else {
                   16253:             $notifylist = $notified[0];
                   16254:         }
                   16255:         $cenv{'internal.notifylist'} = $notifylist;
                   16256:     }
                   16257:     if (@badclasses > 0) {
                   16258:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16259:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16260:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16261:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16262:         );
1.1264    raeburn  16263:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16264:                            &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  16265:         if ($context eq 'auto') {
                   16266:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16267:         } else {
1.566     albertel 16268:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16269:         }
                   16270:         foreach my $item (@badclasses) {
1.541     raeburn  16271:             if ($context eq 'auto') {
1.1261    raeburn  16272:                 $outcome .= " - $item\n";
1.541     raeburn  16273:             } else {
1.1261    raeburn  16274:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16275:             }
1.1261    raeburn  16276:         }
                   16277:         if ($context eq 'auto') {
                   16278:             $outcome .= $linefeed;
                   16279:         } else {
                   16280:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16281:         } 
1.444     albertel 16282:     }
                   16283:     if ($args->{'no_end_date'}) {
                   16284:         $args->{'endaccess'} = 0;
                   16285:     }
                   16286:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16287:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16288:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16289:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16290:     if ($args->{'showphotos'}) {
                   16291:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16292:     }
                   16293:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16294:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16295:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16296:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16297:             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'); 
                   16298:             if ($context eq 'auto') {
                   16299:                 $outcome .= $krb_msg;
                   16300:             } else {
1.566     albertel 16301:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16302:             }
                   16303:             $outcome .= $linefeed;
1.444     albertel 16304:         }
                   16305:     }
                   16306:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16307:        if ($args->{'setpolicy'}) {
                   16308:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16309:        }
                   16310:        if ($args->{'setcontent'}) {
                   16311:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16312:        }
1.1251    raeburn  16313:        if ($args->{'setcomment'}) {
                   16314:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16315:        }
1.444     albertel 16316:     }
                   16317:     if ($args->{'reshome'}) {
                   16318: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16319: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16320:     }
                   16321: #
                   16322: # course has keyed access
                   16323: #
                   16324:     if ($args->{'setkeys'}) {
                   16325:        $cenv{'keyaccess'}='yes';
                   16326:     }
                   16327: # if specified, key authority is not course, but user
                   16328: # only active if keyaccess is yes
                   16329:     if ($args->{'keyauth'}) {
1.487     albertel 16330: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16331: 	$user = &LONCAPA::clean_username($user);
                   16332: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16333: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16334: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16335: 	}
                   16336:     }
                   16337: 
1.1166    raeburn  16338: #
1.1167    raeburn  16339: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16340: #
                   16341:     if ($args->{'uniquecode'}) {
                   16342:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16343:         if ($code) {
                   16344:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16345:             my %crsinfo =
                   16346:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16347:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16348:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16349:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16350:             } 
1.1166    raeburn  16351:             if (ref($coderef)) {
                   16352:                 $$coderef = $code;
                   16353:             }
                   16354:         }
                   16355:     }
                   16356: 
1.444     albertel 16357:     if ($args->{'disresdis'}) {
                   16358:         $cenv{'pch.roles.denied'}='st';
                   16359:     }
                   16360:     if ($args->{'disablechat'}) {
                   16361:         $cenv{'plc.roles.denied'}='st';
                   16362:     }
                   16363: 
                   16364:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16365:     # course
                   16366:     $cenv{'course.helper.not.run'} = 1;
                   16367:     #
                   16368:     # Use new Randomseed
                   16369:     #
                   16370:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16371:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16372:     #
                   16373:     # The encryption code and receipt prefix for this course
                   16374:     #
                   16375:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16376:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16377:     #
                   16378:     # By default, use standard grading
                   16379:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16380: 
1.541     raeburn  16381:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16382:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16383: #
                   16384: # Open all assignments
                   16385: #
                   16386:     if ($args->{'openall'}) {
1.1341    raeburn  16387:        my $opendate = time;
                   16388:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16389:            $opendate = $args->{'openallfrom'};
                   16390:        }
1.444     albertel 16391:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16392:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16393:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16394:        $outcome .= &mt('All assignments open starting [_1]',
                   16395:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16396:                    &Apache::lonnet::cput
                   16397:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16398:    }
                   16399: #
                   16400: # Set first page
                   16401: #
                   16402:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16403: 	    || ($cloneid)) {
1.445     albertel 16404: 	use LONCAPA::map;
1.444     albertel 16405: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16406: 
                   16407: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16408:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16409: 
1.444     albertel 16410:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16411:         my $title; my $url;
                   16412:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16413: 	    $title=&mt('Syllabus');
1.444     albertel 16414:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16415:         } else {
1.963     raeburn  16416:             $title=&mt('Table of Contents');
1.444     albertel 16417:             $url='/adm/navmaps';
                   16418:         }
1.445     albertel 16419: 
                   16420:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16421: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16422: 
                   16423: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16424:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16425:     }
1.566     albertel 16426: 
1.1237    raeburn  16427: # 
                   16428: # Set params for Placement Tests
                   16429: #
1.1239    raeburn  16430:     if ($args->{'crstype'} eq 'Placement') {
                   16431:        my %storecontent; 
                   16432:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16433:        my %defaults = (
                   16434:                         buttonshide   => { value => 'yes',
                   16435:                                            type => 'string_yesno',},
                   16436:                         type          => { value => 'randomizetry',
                   16437:                                            type  => 'string_questiontype',},
                   16438:                         maxtries      => { value => 1,
                   16439:                                            type => 'int_pos',},
                   16440:                         problemstatus => { value => 'no',
                   16441:                                            type  => 'string_problemstatus',},
                   16442:                       );
                   16443:        foreach my $key (keys(%defaults)) {
                   16444:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16445:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16446:        }
1.1237    raeburn  16447:        &Apache::lonnet::cput
                   16448:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16449:     }
                   16450: 
1.1344    raeburn  16451:     return (1,$outcome,\@clonemsg);
1.444     albertel 16452: }
                   16453: 
1.1166    raeburn  16454: sub make_unique_code {
                   16455:     my ($cdom,$cnum) = @_;
                   16456:     # get lock on uniquecodes db
                   16457:     my $lockhash = {
                   16458:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16459:                                                   ':'.$env{'user.domain'},
                   16460:                    };
                   16461:     my $tries = 0;
                   16462:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16463:     my ($code,$error);
                   16464:   
                   16465:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16466:         $tries ++;
                   16467:         sleep 1;
                   16468:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16469:     }
                   16470:     if ($gotlock eq 'ok') {
                   16471:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16472:         my $gotcode;
                   16473:         my $attempts = 0;
                   16474:         while ((!$gotcode) && ($attempts < 100)) {
                   16475:             $code = &generate_code();
                   16476:             if (!exists($currcodes{$code})) {
                   16477:                 $gotcode = 1;
                   16478:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16479:                     $error = 'nostore';
                   16480:                 }
                   16481:             }
                   16482:             $attempts ++;
                   16483:         }
                   16484:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16485:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16486:     } else {
                   16487:         $error = 'nolock';
                   16488:     }
                   16489:     return ($code,$error);
                   16490: }
                   16491: 
                   16492: sub generate_code {
                   16493:     my $code;
                   16494:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16495:     for (my $i=0; $i<6; $i++) {
                   16496:         my $lettnum = int (rand 2);
                   16497:         my $item = '';
                   16498:         if ($lettnum) {
                   16499:             $item = $letts[int( rand(18) )];
                   16500:         } else {
                   16501:             $item = 1+int( rand(8) );
                   16502:         }
                   16503:         $code .= $item;
                   16504:     }
                   16505:     return $code;
                   16506: }
                   16507: 
1.444     albertel 16508: ############################################################
                   16509: ############################################################
                   16510: 
1.1237    raeburn  16511: # Community, Course and Placement Test
1.378     raeburn  16512: sub course_type {
                   16513:     my ($cid) = @_;
                   16514:     if (!defined($cid)) {
                   16515:         $cid = $env{'request.course.id'};
                   16516:     }
1.404     albertel 16517:     if (defined($env{'course.'.$cid.'.type'})) {
                   16518:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16519:     } else {
                   16520:         return 'Course';
1.377     raeburn  16521:     }
                   16522: }
1.156     albertel 16523: 
1.406     raeburn  16524: sub group_term {
                   16525:     my $crstype = &course_type();
                   16526:     my %names = (
                   16527:                   'Course' => 'group',
1.865     raeburn  16528:                   'Community' => 'group',
1.1237    raeburn  16529:                   'Placement' => 'group',
1.406     raeburn  16530:                 );
                   16531:     return $names{$crstype};
                   16532: }
                   16533: 
1.902     raeburn  16534: sub course_types {
1.1310    raeburn  16535:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16536:     my %typename = (
                   16537:                          official   => 'Official course',
                   16538:                          unofficial => 'Unofficial course',
                   16539:                          community  => 'Community',
1.1165    raeburn  16540:                          textbook   => 'Textbook course',
1.1237    raeburn  16541:                          placement  => 'Placement test',
1.1310    raeburn  16542:                          lti        => 'LTI provider',
1.902     raeburn  16543:                    );
                   16544:     return (\@types,\%typename);
                   16545: }
                   16546: 
1.156     albertel 16547: sub icon {
                   16548:     my ($file)=@_;
1.505     albertel 16549:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16550:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16551:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16552:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16553: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16554: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16555: 	            $curfext.".gif") {
                   16556: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16557: 		$curfext.".gif";
                   16558: 	}
                   16559:     }
1.249     albertel 16560:     return &lonhttpdurl($iconname);
1.154     albertel 16561: } 
1.84      albertel 16562: 
1.575     albertel 16563: sub lonhttpdurl {
1.692     www      16564: #
                   16565: # Had been used for "small fry" static images on separate port 8080.
                   16566: # Modify here if lightweight http functionality desired again.
                   16567: # Currently eliminated due to increasing firewall issues.
                   16568: #
1.575     albertel 16569:     my ($url)=@_;
1.692     www      16570:     return $url;
1.215     albertel 16571: }
                   16572: 
1.213     albertel 16573: sub connection_aborted {
                   16574:     my ($r)=@_;
                   16575:     $r->print(" ");$r->rflush();
                   16576:     my $c = $r->connection;
                   16577:     return $c->aborted();
                   16578: }
                   16579: 
1.221     foxr     16580: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16581: #    strings as 'strings'.
                   16582: sub escape_single {
1.221     foxr     16583:     my ($input) = @_;
1.223     albertel 16584:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16585:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16586:     return $input;
                   16587: }
1.223     albertel 16588: 
1.222     foxr     16589: #  Same as escape_single, but escape's "'s  This 
                   16590: #  can be used for  "strings"
                   16591: sub escape_double {
                   16592:     my ($input) = @_;
                   16593:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16594:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16595:     return $input;
                   16596: }
1.223     albertel 16597:  
1.222     foxr     16598: #   Escapes the last element of a full URL.
                   16599: sub escape_url {
                   16600:     my ($url)   = @_;
1.238     raeburn  16601:     my @urlslices = split(/\//, $url,-1);
1.369     www      16602:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16603:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16604: }
1.462     albertel 16605: 
1.820     raeburn  16606: sub compare_arrays {
                   16607:     my ($arrayref1,$arrayref2) = @_;
                   16608:     my (@difference,%count);
                   16609:     @difference = ();
                   16610:     %count = ();
                   16611:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16612:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16613:         foreach my $element (keys(%count)) {
                   16614:             if ($count{$element} == 1) {
                   16615:                 push(@difference,$element);
                   16616:             }
                   16617:         }
                   16618:     }
                   16619:     return @difference;
                   16620: }
                   16621: 
1.1322    raeburn  16622: sub lon_status_items {
                   16623:     my %defaults = (
                   16624:                      E         => 100,
                   16625:                      W         => 4,
                   16626:                      N         => 1,
1.1324    raeburn  16627:                      U         => 5,
1.1322    raeburn  16628:                      threshold => 200,
                   16629:                      sysmail   => 2500,
                   16630:                    );
                   16631:     my %names = (
                   16632:                    E => 'Errors',
                   16633:                    W => 'Warnings',
                   16634:                    N => 'Notices',
1.1324    raeburn  16635:                    U => 'Unsent',
1.1322    raeburn  16636:                 );
                   16637:     return (\%defaults,\%names);
                   16638: }
                   16639: 
1.817     bisitz   16640: # -------------------------------------------------------- Initialize user login
1.462     albertel 16641: sub init_user_environment {
1.463     albertel 16642:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16643:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16644: 
                   16645:     my $public=($username eq 'public' && $domain eq 'public');
                   16646: 
1.1062    raeburn  16647:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16648:     my $now=time;
                   16649: 
                   16650:     if ($public) {
                   16651: 	my $max_public=100;
                   16652: 	my $oldest;
                   16653: 	my $oldest_time=0;
                   16654: 	for(my $next=1;$next<=$max_public;$next++) {
                   16655: 	    if (-e $lonids."/publicuser_$next.id") {
                   16656: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16657: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16658: 		    $oldest_time=$mtime;
                   16659: 		    $oldest=$next;
                   16660: 		}
                   16661: 	    } else {
                   16662: 		$cookie="publicuser_$next";
                   16663: 		last;
                   16664: 	    }
                   16665: 	}
                   16666: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16667:     } else {
1.1275    raeburn  16668: 	# See if old ID present, if so, remove if this isn't a robot,
                   16669: 	# killing any existing non-robot sessions
1.463     albertel 16670: 	if (!$args->{'robot'}) {
                   16671: 	    opendir(DIR,$lonids);
                   16672: 	    while ($filename=readdir(DIR)) {
                   16673: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  16674:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16675:                             &GDBM_READER(),0640)) {
1.1295    raeburn  16676:                         my $linkedfile;
1.1320    raeburn  16677:                         if (exists($oldenv{'user.linkedenv'})) {
                   16678:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  16679:                         }
1.1320    raeburn  16680:                         untie(%oldenv);
                   16681:                         if (unlink("$lonids/$filename")) {
                   16682:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16683:                                 if (-l "$lonids/$linkedfile.id") {
                   16684:                                     unlink("$lonids/$linkedfile.id");
                   16685:                                 }
1.1295    raeburn  16686:                             }
                   16687:                         }
                   16688:                     } else {
                   16689:                         unlink($lonids.'/'.$filename);
                   16690:                     }
1.463     albertel 16691: 		}
1.462     albertel 16692: 	    }
1.463     albertel 16693: 	    closedir(DIR);
1.1204    raeburn  16694: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16695:             my $namespace = 'nohist_courseeditor';
                   16696:             my $lockingkey = 'paste'."\0".'locked_num';
                   16697:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16698:                                                 $domain,$username);
                   16699:             if (exists($lockhash{$lockingkey})) {
                   16700:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16701:                 unless ($delresult eq 'ok') {
                   16702:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16703:                 }
                   16704:             }
1.462     albertel 16705: 	}
                   16706: # Give them a new cookie
1.463     albertel 16707: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16708: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16709: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16710:     
                   16711: # Initialize roles
                   16712: 
1.1062    raeburn  16713: 	($userroles,$firstaccenv,$timerintenv) = 
                   16714:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16715:     }
                   16716: # ------------------------------------ Check browser type and MathML capability
                   16717: 
1.1194    raeburn  16718:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16719:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16720: 
                   16721: # ------------------------------------------------------------- Get environment
                   16722: 
                   16723:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16724:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16725:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16726: 	undef(%userenv);
                   16727:     }
                   16728:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16729: 	$form->{'interface'}=$userenv{'interface'};
                   16730:     }
                   16731:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16732: 
                   16733: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16734:     foreach my $option ('interface','localpath','localres') {
                   16735:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16736:     }
                   16737: # --------------------------------------------------------- Write first profile
                   16738: 
                   16739:     {
                   16740: 	my %initial_env = 
                   16741: 	    ("user.name"          => $username,
                   16742: 	     "user.domain"        => $domain,
                   16743: 	     "user.home"          => $authhost,
                   16744: 	     "browser.type"       => $clientbrowser,
                   16745: 	     "browser.version"    => $clientversion,
                   16746: 	     "browser.mathml"     => $clientmathml,
                   16747: 	     "browser.unicode"    => $clientunicode,
                   16748: 	     "browser.os"         => $clientos,
1.1137    raeburn  16749:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16750:              "browser.info"       => $clientinfo,
1.1194    raeburn  16751:              "browser.osversion"  => $clientosversion,
1.462     albertel 16752: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16753: 	     "request.course.fn"  => '',
                   16754: 	     "request.course.uri" => '',
                   16755: 	     "request.course.sec" => '',
                   16756: 	     "request.role"       => 'cm',
                   16757: 	     "request.role.adv"   => $env{'user.adv'},
                   16758: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16759: 
                   16760:         if ($form->{'localpath'}) {
                   16761: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16762: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16763:         }
                   16764: 	
                   16765: 	if ($form->{'interface'}) {
                   16766: 	    $form->{'interface'}=~s/\W//gs;
                   16767: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16768: 	    $env{'browser.interface'}=$form->{'interface'};
                   16769: 	}
                   16770: 
1.1157    raeburn  16771:         if ($form->{'iptoken'}) {
                   16772:             my $lonhost = $r->dir_config('lonHostID');
                   16773:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16774:             $env{'user.noloadbalance'} = $lonhost;
                   16775:         }
                   16776: 
1.1268    raeburn  16777:         if ($form->{'noloadbalance'}) {
                   16778:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16779:             my $hosthere = $form->{'noloadbalance'};
                   16780:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16781:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16782:                 $env{'user.noloadbalance'} = $hosthere;
                   16783:             }
                   16784:         }
                   16785: 
1.1016    raeburn  16786:         unless ($domain eq 'public') {
1.1273    raeburn  16787:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16788:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16789: 
                   16790:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16791:                 $userenv{'availabletools.'.$tool} = 
                   16792:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16793:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16794:             }
1.980     raeburn  16795: 
1.1311    raeburn  16796:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  16797:                 $userenv{'canrequest.'.$crstype} =
                   16798:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16799:                                                       'reload','requestcourses',
                   16800:                                                       \%userenv,\%domdef,\%is_adv);
                   16801:             }
1.724     raeburn  16802: 
1.1273    raeburn  16803:             $userenv{'canrequest.author'} =
                   16804:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16805:                                                   'reload','requestauthor',
1.980     raeburn  16806:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16807:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16808:                                                  $domain,$username);
                   16809:             my $reqstatus = $reqauthor{'author_status'};
                   16810:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16811:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16812:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16813:                                                       $reqauthor{'author'}{'timestamp'};
                   16814:                 }
1.1092    raeburn  16815:             }
1.1287    raeburn  16816:             my ($types,$typename) = &course_types();
                   16817:             if (ref($types) eq 'ARRAY') {
                   16818:                 my @options = ('approval','validate','autolimit');
                   16819:                 my $optregex = join('|',@options);
                   16820:                 my (%willtrust,%trustchecked);
                   16821:                 foreach my $type (@{$types}) {
                   16822:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   16823:                     if ($dom_str ne '') {
                   16824:                         my $updatedstr = '';
                   16825:                         my @possdomains = split(',',$dom_str);
                   16826:                         foreach my $entry (@possdomains) {
                   16827:                             my ($extdom,$extopt) = split(':',$entry);
                   16828:                             unless ($trustchecked{$extdom}) {
                   16829:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   16830:                                 $trustchecked{$extdom} = 1;
                   16831:                             }
                   16832:                             if ($willtrust{$extdom}) {
                   16833:                                 $updatedstr .= $entry.',';
                   16834:                             }
                   16835:                         }
                   16836:                         $updatedstr =~ s/,$//;
                   16837:                         if ($updatedstr) {
                   16838:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   16839:                         } else {
                   16840:                             delete($userenv{'reqcrsotherdom.'.$type});
                   16841:                         }
                   16842:                     }
                   16843:                 }
                   16844:             }
1.1092    raeburn  16845:         }
1.462     albertel 16846: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16847: 
1.462     albertel 16848: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16849: 		 &GDBM_WRCREAT(),0640)) {
                   16850: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16851: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16852: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16853:             if (ref($firstaccenv) eq 'HASH') {
                   16854:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16855:             }
                   16856:             if (ref($timerintenv) eq 'HASH') {
                   16857:                 &_add_to_env(\%disk_env,$timerintenv);
                   16858:             }
1.463     albertel 16859: 	    if (ref($args->{'extra_env'})) {
                   16860: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16861: 	    }
1.462     albertel 16862: 	    untie(%disk_env);
                   16863: 	} else {
1.705     tempelho 16864: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16865: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16866: 	    return 'error: '.$!;
                   16867: 	}
                   16868:     }
                   16869:     $env{'request.role'}='cm';
                   16870:     $env{'request.role.adv'}=$env{'user.adv'};
                   16871:     $env{'browser.type'}=$clientbrowser;
                   16872: 
                   16873:     return $cookie;
                   16874: 
                   16875: }
                   16876: 
                   16877: sub _add_to_env {
                   16878:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16879:     if (ref($env_data) eq 'HASH') {
                   16880:         while (my ($key,$value) = each(%$env_data)) {
                   16881: 	    $idf->{$prefix.$key} = $value;
                   16882: 	    $env{$prefix.$key}   = $value;
                   16883:         }
1.462     albertel 16884:     }
                   16885: }
                   16886: 
1.685     tempelho 16887: # --- Get the symbolic name of a problem and the url
                   16888: sub get_symb {
                   16889:     my ($request,$silent) = @_;
1.726     raeburn  16890:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16891:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16892:     if ($symb eq '') {
                   16893:         if (!$silent) {
1.1071    raeburn  16894:             if (ref($request)) { 
                   16895:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16896:             }
1.685     tempelho 16897:             return ();
                   16898:         }
                   16899:     }
                   16900:     &Apache::lonenc::check_decrypt(\$symb);
                   16901:     return ($symb);
                   16902: }
                   16903: 
                   16904: # --------------------------------------------------------------Get annotation
                   16905: 
                   16906: sub get_annotation {
                   16907:     my ($symb,$enc) = @_;
                   16908: 
                   16909:     my $key = $symb;
                   16910:     if (!$enc) {
                   16911:         $key =
                   16912:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16913:     }
                   16914:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16915:     return $annotation{$key};
                   16916: }
                   16917: 
                   16918: sub clean_symb {
1.731     raeburn  16919:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16920: 
                   16921:     &Apache::lonenc::check_decrypt(\$symb);
                   16922:     my $enc = $env{'request.enc'};
1.731     raeburn  16923:     if ($delete_enc) {
1.730     raeburn  16924:         delete($env{'request.enc'});
                   16925:     }
1.685     tempelho 16926: 
                   16927:     return ($symb,$enc);
                   16928: }
1.462     albertel 16929: 
1.1181    raeburn  16930: ############################################################
                   16931: ############################################################
                   16932: 
                   16933: =pod
                   16934: 
                   16935: =head1 Routines for building display used to search for courses
                   16936: 
                   16937: 
                   16938: =over 4
                   16939: 
                   16940: =item * &build_filters()
                   16941: 
                   16942: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16943: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16944: and quotacheck.pl
                   16945: 
1.1181    raeburn  16946: 
                   16947: Inputs:
                   16948: 
                   16949: filterlist - anonymous array of fields to include as potential filters 
                   16950: 
                   16951: crstype - course type
                   16952: 
                   16953: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16954:               to pop-open a course selector (will contain "extra element"). 
                   16955: 
                   16956: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16957: 
                   16958: filter - anonymous hash of criteria and their values
                   16959: 
                   16960: action - form action
                   16961: 
                   16962: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16963: 
1.1182    raeburn  16964: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16965: 
                   16966: cloneruname - username of owner of new course who wants to clone
                   16967: 
                   16968: clonerudom - domain of owner of new course who wants to clone
                   16969: 
                   16970: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16971: 
                   16972: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16973: 
                   16974: codedom - domain
                   16975: 
                   16976: formname - value of form element named "form". 
                   16977: 
                   16978: fixeddom - domain, if fixed.
                   16979: 
                   16980: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16981: 
                   16982: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16983: 
                   16984: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16985: 
                   16986: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16987: 
                   16988: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16989: 
                   16990: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16991: 
                   16992: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16993: 
1.1182    raeburn  16994: 
1.1181    raeburn  16995: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16996: 
1.1182    raeburn  16997: 
1.1181    raeburn  16998: Side Effects: None
                   16999: 
                   17000: =cut
                   17001: 
                   17002: # ---------------------------------------------- search for courses based on last activity etc.
                   17003: 
                   17004: sub build_filters {
                   17005:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17006:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17007:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17008:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17009:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17010:     my ($list,$jscript);
1.1181    raeburn  17011:     my $onchange = 'javascript:updateFilters(this)';
                   17012:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17013:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17014:         $typeselectform,$instcodetitle);
                   17015:     if ($formname eq '') {
                   17016:         $formname = $caller;
                   17017:     }
                   17018:     foreach my $item (@{$filterlist}) {
                   17019:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17020:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17021:             if ($item eq 'domainfilter') {
                   17022:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17023:             } elsif ($item eq 'coursefilter') {
                   17024:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17025:             } elsif ($item eq 'ownerfilter') {
                   17026:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17027:             } elsif ($item eq 'ownerdomfilter') {
                   17028:                 $filter->{'ownerdomfilter'} =
                   17029:                     &LONCAPA::clean_domain($filter->{$item});
                   17030:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17031:                                                        'ownerdomfilter',1);
                   17032:             } elsif ($item eq 'personfilter') {
                   17033:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17034:             } elsif ($item eq 'persondomfilter') {
                   17035:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17036:                                                         'persondomfilter',1);
                   17037:             } else {
                   17038:                 $filter->{$item} =~ s/\W//g;
                   17039:             }
                   17040:             if (!$filter->{$item}) {
                   17041:                 $filter->{$item} = '';
                   17042:             }
                   17043:         }
                   17044:         if ($item eq 'domainfilter') {
                   17045:             my $allow_blank = 1;
                   17046:             if ($formname eq 'portform') {
                   17047:                 $allow_blank=0;
                   17048:             } elsif ($formname eq 'studentform') {
                   17049:                 $allow_blank=0;
                   17050:             }
                   17051:             if ($fixeddom) {
                   17052:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17053:                                     ' value="'.$codedom.'" />'.
                   17054:                                     &Apache::lonnet::domain($codedom,'description');
                   17055:             } else {
                   17056:                 $domainselectform = &select_dom_form($filter->{$item},
                   17057:                                                      'domainfilter',
                   17058:                                                       $allow_blank,'',$onchange);
                   17059:             }
                   17060:         } else {
                   17061:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17062:         }
                   17063:     }
                   17064: 
                   17065:     # last course activity filter and selection
                   17066:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17067: 
                   17068:     # course created filter and selection
                   17069:     if (exists($filter->{'createdfilter'})) {
                   17070:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17071:     }
                   17072: 
1.1239    raeburn  17073:     my $prefix = $crstype;
                   17074:     if ($crstype eq 'Placement') {
                   17075:         $prefix = 'Placement Test'
                   17076:     }
1.1181    raeburn  17077:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17078:                 'cac' => "$prefix Activity",
                   17079:                 'ccr' => "$prefix Created",
                   17080:                 'cde' => "$prefix Title",
                   17081:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17082:                 'ins' => 'Institutional Code',
                   17083:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17084:                 'cow' => "$prefix Owner/Co-owner",
                   17085:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17086:                 'cog' => 'Type',
                   17087:              );
                   17088: 
                   17089:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17090:         my $typeval = 'Course';
                   17091:         if ($crstype eq 'Community') {
                   17092:             $typeval = 'Community';
1.1239    raeburn  17093:         } elsif ($crstype eq 'Placement') {
                   17094:             $typeval = 'Placement';
1.1181    raeburn  17095:         }
                   17096:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17097:     } else {
                   17098:         $typeselectform =  '<select name="type" size="1"';
                   17099:         if ($onchange) {
                   17100:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17101:         }
                   17102:         $typeselectform .= '>'."\n";
1.1237    raeburn  17103:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17104:             my $shown;
                   17105:             if ($posstype eq 'Placement') {
                   17106:                 $shown = &mt('Placement Test');
                   17107:             } else {
                   17108:                 $shown = &mt($posstype);
                   17109:             }
1.1181    raeburn  17110:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17111:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17112:         }
                   17113:         $typeselectform.="</select>";
                   17114:     }
                   17115: 
                   17116:     my ($cloneableonlyform,$cloneabletitle);
                   17117:     if (exists($filter->{'cloneableonly'})) {
                   17118:         my $cloneableon = '';
                   17119:         my $cloneableoff = ' checked="checked"';
                   17120:         if ($filter->{'cloneableonly'}) {
                   17121:             $cloneableon = $cloneableoff;
                   17122:             $cloneableoff = '';
                   17123:         }
                   17124:         $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>';
                   17125:         if ($formname eq 'ccrs') {
1.1187    bisitz   17126:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17127:         } else {
                   17128:             $cloneabletitle = &mt('Cloneable by you');
                   17129:         }
                   17130:     }
                   17131:     my $officialjs;
                   17132:     if ($crstype eq 'Course') {
                   17133:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17134: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17135: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17136:             if ($codedom) { 
1.1181    raeburn  17137:                 $officialjs = 1;
                   17138:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17139:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17140:                                                                   $officialjs,$codetitlesref);
                   17141:                 if ($jscript) {
1.1182    raeburn  17142:                     $jscript = '<script type="text/javascript">'."\n".
                   17143:                                '// <![CDATA['."\n".
                   17144:                                $jscript."\n".
                   17145:                                '// ]]>'."\n".
                   17146:                                '</script>'."\n";
1.1181    raeburn  17147:                 }
                   17148:             }
                   17149:             if ($instcodeform eq '') {
                   17150:                 $instcodeform =
                   17151:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17152:                     $list->{'instcodefilter'}.'" />';
                   17153:                 $instcodetitle = $lt{'ins'};
                   17154:             } else {
                   17155:                 $instcodetitle = $lt{'inc'};
                   17156:             }
                   17157:             if ($fixeddom) {
                   17158:                 $instcodetitle .= '<br />('.$codedom.')';
                   17159:             }
                   17160:         }
                   17161:     }
                   17162:     my $output = qq|
                   17163: <form method="post" name="filterpicker" action="$action">
                   17164: <input type="hidden" name="form" value="$formname" />
                   17165: |;
                   17166:     if ($formname eq 'modifycourse') {
                   17167:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17168:                    '<input type="hidden" name="prevphase" value="'.
                   17169:                    $prevphase.'" />'."\n";
1.1198    musolffc 17170:     } elsif ($formname eq 'quotacheck') {
                   17171:         $output .= qq|
                   17172: <input type="hidden" name="sortby" value="" />
                   17173: <input type="hidden" name="sortorder" value="" />
                   17174: |;
                   17175:     } else {
1.1181    raeburn  17176:         my $name_input;
                   17177:         if ($cnameelement ne '') {
                   17178:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17179:                           $cnameelement.'" />';
                   17180:         }
                   17181:         $output .= qq|
1.1182    raeburn  17182: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17183: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17184: $name_input
                   17185: $roleelement
                   17186: $multelement
                   17187: $typeelement
                   17188: |;
                   17189:         if ($formname eq 'portform') {
                   17190:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17191:         }
                   17192:     }
                   17193:     if ($fixeddom) {
                   17194:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17195:     }
                   17196:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17197:     if ($sincefilterform) {
                   17198:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17199:                   .$sincefilterform
                   17200:                   .&Apache::lonhtmlcommon::row_closure();
                   17201:     }
                   17202:     if ($createdfilterform) {
                   17203:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17204:                   .$createdfilterform
                   17205:                   .&Apache::lonhtmlcommon::row_closure();
                   17206:     }
                   17207:     if ($domainselectform) {
                   17208:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17209:                   .$domainselectform
                   17210:                   .&Apache::lonhtmlcommon::row_closure();
                   17211:     }
                   17212:     if ($typeselectform) {
                   17213:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17214:             $output .= $typeselectform;
                   17215:         } else {
                   17216:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17217:                       .$typeselectform
                   17218:                       .&Apache::lonhtmlcommon::row_closure();
                   17219:         }
                   17220:     }
                   17221:     if ($instcodeform) {
                   17222:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17223:                   .$instcodeform
                   17224:                   .&Apache::lonhtmlcommon::row_closure();
                   17225:     }
                   17226:     if (exists($filter->{'ownerfilter'})) {
                   17227:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17228:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17229:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17230:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17231:                    $ownerdomselectform.'</td></tr></table>'.
                   17232:                    &Apache::lonhtmlcommon::row_closure();
                   17233:     }
                   17234:     if (exists($filter->{'personfilter'})) {
                   17235:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17236:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17237:                    '<input type="text" name="personfilter" size="20" value="'.
                   17238:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17239:                    $persondomselectform.'</td></tr></table>'.
                   17240:                    &Apache::lonhtmlcommon::row_closure();
                   17241:     }
                   17242:     if (exists($filter->{'coursefilter'})) {
                   17243:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17244:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17245:                   .$list->{'coursefilter'}.'" />'
                   17246:                   .&Apache::lonhtmlcommon::row_closure();
                   17247:     }
                   17248:     if ($cloneableonlyform) {
                   17249:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17250:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17251:     }
                   17252:     if (exists($filter->{'descriptfilter'})) {
                   17253:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17254:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17255:                   .$list->{'descriptfilter'}.'" />'
                   17256:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17257:     }
                   17258:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17259:                '<input type="hidden" name="updater" value="" />'."\n".
                   17260:                '<input type="submit" name="gosearch" value="'.
                   17261:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17262:     return $jscript.$clonewarning.$output;
                   17263: }
                   17264: 
                   17265: =pod 
                   17266: 
                   17267: =item * &timebased_select_form()
                   17268: 
1.1182    raeburn  17269: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17270: filter e.g., Course Activity, Course Created, when searching for courses
                   17271: or communities
                   17272: 
                   17273: Inputs:
                   17274: 
                   17275: item - name of form element (sincefilter or createdfilter)
                   17276: 
                   17277: filter - anonymous hash of criteria and their values
                   17278: 
                   17279: Returns: HTML for a select box contained a blank, then six time selections,
                   17280:          with value set in incoming form variables currently selected. 
                   17281: 
                   17282: Side Effects: None
                   17283: 
                   17284: =cut
                   17285: 
                   17286: sub timebased_select_form {
                   17287:     my ($item,$filter) = @_;
                   17288:     if (ref($filter) eq 'HASH') {
                   17289:         $filter->{$item} =~ s/[^\d-]//g;
                   17290:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17291:         return &select_form(
                   17292:                             $filter->{$item},
                   17293:                             $item,
                   17294:                             {      '-1' => '',
                   17295:                                 '86400' => &mt('today'),
                   17296:                                '604800' => &mt('last week'),
                   17297:                               '2592000' => &mt('last month'),
                   17298:                               '7776000' => &mt('last three months'),
                   17299:                              '15552000' => &mt('last six months'),
                   17300:                              '31104000' => &mt('last year'),
                   17301:                     'select_form_order' =>
                   17302:                            ['-1','86400','604800','2592000','7776000',
                   17303:                             '15552000','31104000']});
                   17304:     }
                   17305: }
                   17306: 
                   17307: =pod
                   17308: 
                   17309: =item * &js_changer()
                   17310: 
                   17311: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17312: when course type or domain is changed, and also to hide 'Searching ...' on
                   17313: page load completion for page showing search result.
1.1181    raeburn  17314: 
                   17315: Inputs: None
                   17316: 
1.1183    raeburn  17317: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17318: 
                   17319: Side Effects: None
                   17320: 
                   17321: =cut
                   17322: 
                   17323: sub js_changer {
                   17324:     return <<ENDJS;
                   17325: <script type="text/javascript">
                   17326: // <![CDATA[
                   17327: function updateFilters(caller) {
                   17328:     if (typeof(caller) != "undefined") {
                   17329:         document.filterpicker.updater.value = caller.name;
                   17330:     }
                   17331:     document.filterpicker.submit();
                   17332: }
1.1183    raeburn  17333: 
                   17334: function hideSearching() {
                   17335:     if (document.getElementById('searching')) {
                   17336:         document.getElementById('searching').style.display = 'none';
                   17337:     }
                   17338:     return;
                   17339: }
                   17340: 
1.1181    raeburn  17341: // ]]>
                   17342: </script>
                   17343: 
                   17344: ENDJS
                   17345: }
                   17346: 
                   17347: =pod
                   17348: 
1.1182    raeburn  17349: =item * &search_courses()
                   17350: 
                   17351: Process selected filters form course search form and pass to lonnet::courseiddump
                   17352: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17353: 
                   17354: Inputs:
                   17355: 
                   17356: dom - domain being searched 
                   17357: 
                   17358: type - course type ('Course' or 'Community' or '.' if any).
                   17359: 
                   17360: filter - anonymous hash of criteria and their values
                   17361: 
                   17362: numtitles - for institutional codes - number of categories
                   17363: 
                   17364: cloneruname - optional username of new course owner
                   17365: 
                   17366: clonerudom - optional domain of new course owner
                   17367: 
1.1221    raeburn  17368: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17369:             (used when DC is using course creation form)
                   17370: 
                   17371: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17372: 
1.1221    raeburn  17373: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17374:            (and so can clone automatically)
                   17375: 
                   17376: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17377: 
                   17378: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17379:               courses to clone 
1.1182    raeburn  17380: 
                   17381: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17382: 
                   17383: 
                   17384: Side Effects: None
                   17385: 
                   17386: =cut
                   17387: 
                   17388: 
                   17389: sub search_courses {
1.1221    raeburn  17390:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17391:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17392:     my (%courses,%showcourses,$cloner);
                   17393:     if (($filter->{'ownerfilter'} ne '') ||
                   17394:         ($filter->{'ownerdomfilter'} ne '')) {
                   17395:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17396:                                        $filter->{'ownerdomfilter'};
                   17397:     }
                   17398:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17399:         if (!$filter->{$item}) {
                   17400:             $filter->{$item}='.';
                   17401:         }
                   17402:     }
                   17403:     my $now = time;
                   17404:     my $timefilter =
                   17405:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17406:     my ($createdbefore,$createdafter);
                   17407:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17408:         $createdbefore = $now;
                   17409:         $createdafter = $now-$filter->{'createdfilter'};
                   17410:     }
                   17411:     my ($instcodefilter,$regexpok);
                   17412:     if ($numtitles) {
                   17413:         if ($env{'form.official'} eq 'on') {
                   17414:             $instcodefilter =
                   17415:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17416:             $regexpok = 1;
                   17417:         } elsif ($env{'form.official'} eq 'off') {
                   17418:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17419:             unless ($instcodefilter eq '') {
                   17420:                 $regexpok = -1;
                   17421:             }
                   17422:         }
                   17423:     } else {
                   17424:         $instcodefilter = $filter->{'instcodefilter'};
                   17425:     }
                   17426:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17427:     if ($type eq '') { $type = '.'; }
                   17428: 
                   17429:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17430:         $cloner = $cloneruname.':'.$clonerudom;
                   17431:     }
                   17432:     %courses = &Apache::lonnet::courseiddump($dom,
                   17433:                                              $filter->{'descriptfilter'},
                   17434:                                              $timefilter,
                   17435:                                              $instcodefilter,
                   17436:                                              $filter->{'combownerfilter'},
                   17437:                                              $filter->{'coursefilter'},
                   17438:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17439:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17440:                                              $filter->{'cloneableonly'},
                   17441:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17442:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17443:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17444:         my $ccrole;
                   17445:         if ($type eq 'Community') {
                   17446:             $ccrole = 'co';
                   17447:         } else {
                   17448:             $ccrole = 'cc';
                   17449:         }
                   17450:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17451:                                                      $filter->{'persondomfilter'},
                   17452:                                                      'userroles',undef,
                   17453:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17454:                                                      $dom);
                   17455:         foreach my $role (keys(%rolehash)) {
                   17456:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17457:             my $cid = $cdom.'_'.$cnum;
                   17458:             if (exists($courses{$cid})) {
                   17459:                 if (ref($courses{$cid}) eq 'HASH') {
                   17460:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17461:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17462:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17463:                         }
                   17464:                     } else {
                   17465:                         $courses{$cid}{roles} = [$courserole];
                   17466:                     }
                   17467:                     $showcourses{$cid} = $courses{$cid};
                   17468:                 }
                   17469:             }
                   17470:         }
                   17471:         %courses = %showcourses;
                   17472:     }
                   17473:     return %courses;
                   17474: }
                   17475: 
                   17476: =pod
                   17477: 
1.1181    raeburn  17478: =back
                   17479: 
1.1207    raeburn  17480: =head1 Routines for version requirements for current course.
                   17481: 
                   17482: =over 4
                   17483: 
                   17484: =item * &check_release_required()
                   17485: 
                   17486: Compares required LON-CAPA version with version on server, and
                   17487: if required version is newer looks for a server with the required version.
                   17488: 
                   17489: Looks first at servers in user's owen domain; if none suitable, looks at
                   17490: servers in course's domain are permitted to host sessions for user's domain.
                   17491: 
                   17492: Inputs:
                   17493: 
                   17494: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17495: 
                   17496: $courseid - Course ID of current course
                   17497: 
                   17498: $rolecode - User's current role in course (for switchserver query string).
                   17499: 
                   17500: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17501: 
                   17502: 
                   17503: Returns:
                   17504: 
                   17505: $switchserver - query string tp append to /adm/switchserver call (if 
                   17506:                 current server's LON-CAPA version is too old. 
                   17507: 
                   17508: $warning - Message is displayed if no suitable server could be found.
                   17509: 
                   17510: =cut
                   17511: 
                   17512: sub check_release_required {
                   17513:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17514:     my ($switchserver,$warning);
                   17515:     if ($required ne '') {
                   17516:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17517:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17518:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17519:             my $otherserver;
                   17520:             if (($major eq '' && $minor eq '') ||
                   17521:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17522:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17523:                 my $switchlcrev =
                   17524:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17525:                                                            $userdomserver);
                   17526:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17527:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17528:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17529:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17530:                     if ($cdom ne $env{'user.domain'}) {
                   17531:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17532:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17533:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17534:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17535:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17536:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17537:                         my $canhost =
                   17538:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17539:                                                               $coursedomserver,
                   17540:                                                               $remoterev,
                   17541:                                                               $udomdefaults{'remotesessions'},
                   17542:                                                               $defdomdefaults{'hostedsessions'});
                   17543: 
                   17544:                         if ($canhost) {
                   17545:                             $otherserver = $coursedomserver;
                   17546:                         } else {
                   17547:                             $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.");
                   17548:                         }
                   17549:                     } else {
                   17550:                         $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).");
                   17551:                     }
                   17552:                 } else {
                   17553:                     $otherserver = $userdomserver;
                   17554:                 }
                   17555:             }
                   17556:             if ($otherserver ne '') {
                   17557:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17558:             }
                   17559:         }
                   17560:     }
                   17561:     return ($switchserver,$warning);
                   17562: }
                   17563: 
                   17564: =pod
                   17565: 
                   17566: =item * &check_release_result()
                   17567: 
                   17568: Inputs:
                   17569: 
                   17570: $switchwarning - Warning message if no suitable server found to host session.
                   17571: 
                   17572: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17573:                 and current role.
                   17574: 
                   17575: Returns: HTML to display with information about requirement to switch server.
                   17576:          Either displaying warning with link to Roles/Courses screen or
                   17577:          display link to switchserver.
                   17578: 
1.1181    raeburn  17579: =cut
                   17580: 
1.1207    raeburn  17581: sub check_release_result {
                   17582:     my ($switchwarning,$switchserver) = @_;
                   17583:     my $output = &start_page('Selected course unavailable on this server').
                   17584:                  '<p class="LC_warning">';
                   17585:     if ($switchwarning) {
                   17586:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17587:         if (&show_course()) {
                   17588:             $output .= &mt('Display courses');
                   17589:         } else {
                   17590:             $output .= &mt('Display roles');
                   17591:         }
                   17592:         $output .= '</a>';
                   17593:     } elsif ($switchserver) {
                   17594:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17595:                    '<br />'.
                   17596:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17597:                    &mt('Switch Server').
                   17598:                    '</a>';
                   17599:     }
                   17600:     $output .= '</p>'.&end_page();
                   17601:     return $output;
                   17602: }
                   17603: 
                   17604: =pod
                   17605: 
                   17606: =item * &needs_coursereinit()
                   17607: 
                   17608: Determine if course contents stored for user's session needs to be
                   17609: refreshed, because content has changed since "Big Hash" last tied.
                   17610: 
                   17611: Check for change is made if time last checked is more than 10 minutes ago
                   17612: (by default).
                   17613: 
                   17614: Inputs:
                   17615: 
                   17616: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17617: 
                   17618: $interval (optional) - Time which may elapse (in s) between last check for content
                   17619:                        change in current course. (default: 600 s).  
                   17620: 
                   17621: Returns: an array; first element is:
                   17622: 
                   17623: =over 4
                   17624: 
                   17625: 'switch' - if content updates mean user's session
                   17626:            needs to be switched to a server running a newer LON-CAPA version
                   17627:  
                   17628: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17629:            on current server hosting user's session                
                   17630: 
                   17631: ''       - if no action required.
                   17632: 
                   17633: =back
                   17634: 
                   17635: If first item element is 'switch':
                   17636: 
                   17637: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17638: 
                   17639: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17640:                               and current role. 
                   17641: 
                   17642: otherwise: no other elements returned.
                   17643: 
                   17644: =back
                   17645: 
                   17646: =cut
                   17647: 
                   17648: sub needs_coursereinit {
                   17649:     my ($loncaparev,$interval) = @_;
                   17650:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17651:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17652:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17653:     my $now = time;
                   17654:     if ($interval eq '') {
                   17655:         $interval = 600;
                   17656:     }
                   17657:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17658:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17659:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17660:         if ($blocked) {
                   17661:             return ();
                   17662:         }
1.1207    raeburn  17663:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17664:         if ($lastchange > $env{'request.course.tied'}) {
                   17665:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17666:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17667:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17668:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17669:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17670:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17671:                     my ($switchserver,$switchwarning) =
                   17672:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17673:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17674:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17675:                         return ('switch',$switchwarning,$switchserver);
                   17676:                     }
                   17677:                 }
                   17678:             }
                   17679:             return ('update');
                   17680:         }
                   17681:     }
                   17682:     return ();
                   17683: }
1.1181    raeburn  17684: 
1.1083    raeburn  17685: sub update_content_constraints {
1.1326    raeburn  17686:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  17687:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17688:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  17689:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  17690:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17691:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17692:         if ($item eq 'resourcetag') {
                   17693:             if ($name eq 'responsetype') {
                   17694:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17695:             }
1.1307    raeburn  17696:         } elsif ($item eq 'course') {
                   17697:             if ($name eq 'courserestype') {
                   17698:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   17699:             }
1.1083    raeburn  17700:         }
                   17701:     }
                   17702:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17703:     if (defined($navmap)) {
1.1307    raeburn  17704:         my (%allresponses,%allcrsrestypes);
                   17705:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   17706:             if ($res->is_tool()) {
                   17707:                 if ($allcrsrestypes{'exttool'}) {
                   17708:                     $allcrsrestypes{'exttool'} ++;
                   17709:                 } else {
                   17710:                     $allcrsrestypes{'exttool'} = 1;
                   17711:                 }
                   17712:                 next;
                   17713:             }
1.1083    raeburn  17714:             my %responses = $res->responseTypes();
                   17715:             foreach my $key (keys(%responses)) {
                   17716:                 next unless(exists($checkresponsetypes{$key}));
                   17717:                 $allresponses{$key} += $responses{$key};
                   17718:             }
                   17719:         }
                   17720:         foreach my $key (keys(%allresponses)) {
                   17721:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17722:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17723:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17724:             }
                   17725:         }
1.1307    raeburn  17726:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  17727:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  17728:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17729:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17730:             }
                   17731:         }
1.1083    raeburn  17732:         undef($navmap);
                   17733:     }
1.1326    raeburn  17734:     my (@resources,@order,@resparms,@zombies);
                   17735:     if ($keeporder) {
                   17736:         use LONCAPA::map;
                   17737:         @resources = @LONCAPA::map::resources;
                   17738:         @order = @LONCAPA::map::order;
                   17739:         @resparms = @LONCAPA::map::resparms;
                   17740:         @zombies = @LONCAPA::map::zombies;
                   17741:     }
1.1308    raeburn  17742:     my $suppmap = 'supplemental.sequence';
                   17743:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   17744:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   17745:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  17746:     if ($keeporder) {
                   17747:         @LONCAPA::map::resources = @resources;
                   17748:         @LONCAPA::map::order = @order;
                   17749:         @LONCAPA::map::resparms = @resparms;
                   17750:         @LONCAPA::map::zombies = @zombies;
                   17751:     }
1.1308    raeburn  17752:     if ($supptools) {
                   17753:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   17754:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17755:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   17756:         }
                   17757:     }
1.1083    raeburn  17758:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17759:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17760:     }
                   17761:     return;
                   17762: }
                   17763: 
1.1110    raeburn  17764: sub allmaps_incourse {
                   17765:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17766:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17767:         $cid = $env{'request.course.id'};
                   17768:         $cdom = $env{'course.'.$cid.'.domain'};
                   17769:         $cnum = $env{'course.'.$cid.'.num'};
                   17770:         $chome = $env{'course.'.$cid.'.home'};
                   17771:     }
                   17772:     my %allmaps = ();
                   17773:     my $lastchange =
                   17774:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17775:     if ($lastchange > $env{'request.course.tied'}) {
                   17776:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17777:         unless ($ferr) {
1.1326    raeburn  17778:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  17779:         }
                   17780:     }
                   17781:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17782:     if (defined($navmap)) {
                   17783:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17784:             $allmaps{$res->src()} = 1;
                   17785:         }
                   17786:     }
                   17787:     return \%allmaps;
                   17788: }
                   17789: 
1.1083    raeburn  17790: sub parse_supplemental_title {
                   17791:     my ($title) = @_;
                   17792: 
                   17793:     my ($foldertitle,$renametitle);
                   17794:     if ($title =~ /&amp;&amp;&amp;/) {
                   17795:         $title = &HTML::Entites::decode($title);
                   17796:     }
                   17797:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17798:         $renametitle=$4;
                   17799:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17800:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17801:         my $name =  &plainname($uname,$udom);
                   17802:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17803:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17804:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17805:             $name.': <br />'.$foldertitle;
                   17806:     }
                   17807:     if (wantarray) {
                   17808:         return ($title,$foldertitle,$renametitle);
                   17809:     }
                   17810:     return $title;
                   17811: }
                   17812: 
1.1143    raeburn  17813: sub recurse_supplemental {
1.1308    raeburn  17814:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  17815:     if ($suppmap) {
                   17816:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17817:         if ($fatal) {
                   17818:             $errors ++;
                   17819:         } else {
                   17820:             if ($#LONCAPA::map::resources > 0) {
                   17821:                 foreach my $res (@LONCAPA::map::resources) {
                   17822:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17823:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17824:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  17825:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   17826:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  17827:                         } else {
1.1308    raeburn  17828:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   17829:                                 $numexttools ++;
                   17830:                             }
1.1143    raeburn  17831:                             $numfiles ++;
                   17832:                         }
                   17833:                     }
                   17834:                 }
                   17835:             }
                   17836:         }
                   17837:     }
1.1308    raeburn  17838:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  17839: }
                   17840: 
1.1101    raeburn  17841: sub symb_to_docspath {
1.1267    raeburn  17842:     my ($symb,$navmapref) = @_;
                   17843:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17844:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17845:     if ($resurl=~/\.(sequence|page)$/) {
                   17846:         $mapurl=$resurl;
                   17847:     } elsif ($resurl eq 'adm/navmaps') {
                   17848:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17849:     }
                   17850:     my $mapresobj;
1.1267    raeburn  17851:     unless (ref($$navmapref)) {
                   17852:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17853:     }
                   17854:     if (ref($$navmapref)) {
                   17855:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17856:     }
                   17857:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17858:     my $type=$2;
                   17859:     my $path;
                   17860:     if (ref($mapresobj)) {
                   17861:         my $pcslist = $mapresobj->map_hierarchy();
                   17862:         if ($pcslist ne '') {
                   17863:             foreach my $pc (split(/,/,$pcslist)) {
                   17864:                 next if ($pc <= 1);
1.1267    raeburn  17865:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17866:                 if (ref($res)) {
                   17867:                     my $thisurl = $res->src();
                   17868:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17869:                     my $thistitle = $res->title();
                   17870:                     $path .= '&'.
                   17871:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17872:                              &escape($thistitle).
1.1101    raeburn  17873:                              ':'.$res->randompick().
                   17874:                              ':'.$res->randomout().
                   17875:                              ':'.$res->encrypted().
                   17876:                              ':'.$res->randomorder().
                   17877:                              ':'.$res->is_page();
                   17878:                 }
                   17879:             }
                   17880:         }
                   17881:         $path =~ s/^\&//;
                   17882:         my $maptitle = $mapresobj->title();
                   17883:         if ($mapurl eq 'default') {
1.1129    raeburn  17884:             $maptitle = 'Main Content';
1.1101    raeburn  17885:         }
                   17886:         $path .= (($path ne '')? '&' : '').
                   17887:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17888:                  &escape($maptitle).
1.1101    raeburn  17889:                  ':'.$mapresobj->randompick().
                   17890:                  ':'.$mapresobj->randomout().
                   17891:                  ':'.$mapresobj->encrypted().
                   17892:                  ':'.$mapresobj->randomorder().
                   17893:                  ':'.$mapresobj->is_page();
                   17894:     } else {
                   17895:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17896:         my $ispage = (($type eq 'page')? 1 : '');
                   17897:         if ($mapurl eq 'default') {
1.1129    raeburn  17898:             $maptitle = 'Main Content';
1.1101    raeburn  17899:         }
                   17900:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17901:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17902:     }
                   17903:     unless ($mapurl eq 'default') {
                   17904:         $path = 'default&'.
1.1146    raeburn  17905:                 &escape('Main Content').
1.1101    raeburn  17906:                 ':::::&'.$path;
                   17907:     }
                   17908:     return $path;
                   17909: }
                   17910: 
1.1094    raeburn  17911: sub captcha_display {
1.1327    raeburn  17912:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17913:     my ($output,$error);
1.1234    raeburn  17914:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  17915:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17916:     if ($captcha eq 'original') {
1.1094    raeburn  17917:         $output = &create_captcha();
                   17918:         unless ($output) {
1.1172    raeburn  17919:             $error = 'captcha';
1.1094    raeburn  17920:         }
                   17921:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17922:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17923:         unless ($output) {
1.1172    raeburn  17924:             $error = 'recaptcha';
1.1094    raeburn  17925:         }
                   17926:     }
1.1234    raeburn  17927:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17928: }
                   17929: 
                   17930: sub captcha_response {
1.1327    raeburn  17931:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17932:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  17933:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17934:     if ($captcha eq 'original') {
1.1094    raeburn  17935:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17936:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17937:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17938:     } else {
                   17939:         $captcha_chk = 1;
                   17940:     }
                   17941:     return ($captcha_chk,$captcha_error);
                   17942: }
                   17943: 
                   17944: sub get_captcha_config {
1.1327    raeburn  17945:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  17946:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17947:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17948:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17949:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17950:     if ($context eq 'usercreation') {
                   17951:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17952:         if (ref($domconfig{$context}) eq 'HASH') {
                   17953:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17954:             if (ref($hashtocheck) eq 'HASH') {
                   17955:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17956:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17957:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17958:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17959:                     }
                   17960:                     if ($privkey && $pubkey) {
                   17961:                         $captcha = 'recaptcha';
1.1234    raeburn  17962:                         $version = $hashtocheck->{'recaptchaversion'};
                   17963:                         if ($version ne '2') {
                   17964:                             $version = 1;
                   17965:                         }
1.1095    raeburn  17966:                     } else {
                   17967:                         $captcha = 'original';
                   17968:                     }
                   17969:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17970:                     $captcha = 'original';
                   17971:                 }
1.1094    raeburn  17972:             }
1.1095    raeburn  17973:         } else {
                   17974:             $captcha = 'captcha';
                   17975:         }
                   17976:     } elsif ($context eq 'login') {
                   17977:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17978:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17979:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17980:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17981:             if ($privkey && $pubkey) {
                   17982:                 $captcha = 'recaptcha';
1.1234    raeburn  17983:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17984:                 if ($version ne '2') {
                   17985:                     $version = 1; 
                   17986:                 }
1.1095    raeburn  17987:             } else {
                   17988:                 $captcha = 'original';
1.1094    raeburn  17989:             }
1.1095    raeburn  17990:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17991:             $captcha = 'original';
1.1094    raeburn  17992:         }
1.1327    raeburn  17993:     } elsif ($context eq 'passwords') {
                   17994:         if ($dom_in_effect) {
                   17995:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17996:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17997:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17998:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17999:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18000:                 }
                   18001:                 if ($privkey && $pubkey) {
                   18002:                     $captcha = 'recaptcha';
                   18003:                     $version = $passwdconf{'recaptchaversion'};
                   18004:                     if ($version ne '2') {
                   18005:                         $version = 1;
                   18006:                     }
                   18007:                 } else {
                   18008:                     $captcha = 'original';
                   18009:                 }
                   18010:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18011:                 $captcha = 'original';
                   18012:             }
                   18013:         }
                   18014:     } 
1.1234    raeburn  18015:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18016: }
                   18017: 
                   18018: sub create_captcha {
                   18019:     my %captcha_params = &captcha_settings();
                   18020:     my ($output,$maxtries,$tries) = ('',10,0);
                   18021:     while ($tries < $maxtries) {
                   18022:         $tries ++;
                   18023:         my $captcha = Authen::Captcha->new (
                   18024:                                            output_folder => $captcha_params{'output_dir'},
                   18025:                                            data_folder   => $captcha_params{'db_dir'},
                   18026:                                           );
                   18027:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18028: 
                   18029:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18030:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   18031:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18032:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   18033:                       '<br />'.
                   18034:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18035:             last;
                   18036:         }
                   18037:     }
1.1323    raeburn  18038:     if ($output eq '') {
                   18039:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18040:     }
1.1094    raeburn  18041:     return $output;
                   18042: }
                   18043: 
                   18044: sub captcha_settings {
                   18045:     my %captcha_params = (
                   18046:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18047:                            www_output_dir => "/captchaspool",
                   18048:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18049:                            numchars       => '5',
                   18050:                          );
                   18051:     return %captcha_params;
                   18052: }
                   18053: 
                   18054: sub check_captcha {
                   18055:     my ($captcha_chk,$captcha_error);
                   18056:     my $code = $env{'form.code'};
                   18057:     my $md5sum = $env{'form.crypt'};
                   18058:     my %captcha_params = &captcha_settings();
                   18059:     my $captcha = Authen::Captcha->new(
                   18060:                       output_folder => $captcha_params{'output_dir'},
                   18061:                       data_folder   => $captcha_params{'db_dir'},
                   18062:                   );
1.1109    raeburn  18063:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18064:     my %captcha_hash = (
                   18065:                         0       => 'Code not checked (file error)',
                   18066:                        -1      => 'Failed: code expired',
                   18067:                        -2      => 'Failed: invalid code (not in database)',
                   18068:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18069:     );
                   18070:     if ($captcha_chk != 1) {
                   18071:         $captcha_error = $captcha_hash{$captcha_chk}
                   18072:     }
                   18073:     return ($captcha_chk,$captcha_error);
                   18074: }
                   18075: 
                   18076: sub create_recaptcha {
1.1234    raeburn  18077:     my ($pubkey,$version) = @_;
                   18078:     if ($version >= 2) {
                   18079:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   18080:     } else {
                   18081:         my $use_ssl;
                   18082:         if ($ENV{'SERVER_PORT'} == 443) {
                   18083:             $use_ssl = 1;
                   18084:         }
                   18085:         my $captcha = Captcha::reCAPTCHA->new;
                   18086:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18087:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18088:                &mt('If the text is hard to read, [_1] will replace them.',
                   18089:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18090:                '<br /><br />';
                   18091:     }
1.1094    raeburn  18092: }
                   18093: 
                   18094: sub check_recaptcha {
1.1234    raeburn  18095:     my ($privkey,$version) = @_;
1.1094    raeburn  18096:     my $captcha_chk;
1.1234    raeburn  18097:     if ($version >= 2) {
                   18098:         my %info = (
                   18099:                      secret   => $privkey, 
                   18100:                      response => $env{'form.g-recaptcha-response'},
                   18101:                      remoteip => $ENV{'REMOTE_ADDR'},
                   18102:                    );
1.1280    raeburn  18103:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18104:         $request->content(join('&',map {
                   18105:                          my $name = escape($_);
                   18106:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18107:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18108:                          : &escape($info{$_}) );
                   18109:         } keys(%info)));
                   18110:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18111:         if ($response->is_success)  {
                   18112:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18113:             if (ref($data) eq 'HASH') {
                   18114:                 if ($data->{'success'}) {
                   18115:                     $captcha_chk = 1;
                   18116:                 }
                   18117:             }
                   18118:         }
                   18119:     } else {
                   18120:         my $captcha = Captcha::reCAPTCHA->new;
                   18121:         my $captcha_result =
                   18122:             $captcha->check_answer(
                   18123:                                     $privkey,
                   18124:                                     $ENV{'REMOTE_ADDR'},
                   18125:                                     $env{'form.recaptcha_challenge_field'},
                   18126:                                     $env{'form.recaptcha_response_field'},
                   18127:                                   );
                   18128:         if ($captcha_result->{is_valid}) {
                   18129:             $captcha_chk = 1;
                   18130:         }
1.1094    raeburn  18131:     }
                   18132:     return $captcha_chk;
                   18133: }
                   18134: 
1.1174    raeburn  18135: sub emailusername_info {
1.1244    raeburn  18136:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18137:     my %titles = &Apache::lonlocal::texthash (
                   18138:                      lastname      => 'Last Name',
                   18139:                      firstname     => 'First Name',
                   18140:                      institution   => 'School/college/university',
                   18141:                      location      => "School's city, state/province, country",
                   18142:                      web           => "School's web address",
                   18143:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18144:                      id            => 'Student/Employee ID',
1.1174    raeburn  18145:                  );
                   18146:     return (\@fields,\%titles);
                   18147: }
                   18148: 
1.1161    raeburn  18149: sub cleanup_html {
                   18150:     my ($incoming) = @_;
                   18151:     my $outgoing;
                   18152:     if ($incoming ne '') {
                   18153:         $outgoing = $incoming;
                   18154:         $outgoing =~ s/;/&#059;/g;
                   18155:         $outgoing =~ s/\#/&#035;/g;
                   18156:         $outgoing =~ s/\&/&#038;/g;
                   18157:         $outgoing =~ s/</&#060;/g;
                   18158:         $outgoing =~ s/>/&#062;/g;
                   18159:         $outgoing =~ s/\(/&#040/g;
                   18160:         $outgoing =~ s/\)/&#041;/g;
                   18161:         $outgoing =~ s/"/&#034;/g;
                   18162:         $outgoing =~ s/'/&#039;/g;
                   18163:         $outgoing =~ s/\$/&#036;/g;
                   18164:         $outgoing =~ s{/}{&#047;}g;
                   18165:         $outgoing =~ s/=/&#061;/g;
                   18166:         $outgoing =~ s/\\/&#092;/g
                   18167:     }
                   18168:     return $outgoing;
                   18169: }
                   18170: 
1.1190    musolffc 18171: # Checks for critical messages and returns a redirect url if one exists.
                   18172: # $interval indicates how often to check for messages.
1.1282    raeburn  18173: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18174: sub critical_redirect {
1.1282    raeburn  18175:     my ($interval,$context) = @_;
1.1190    musolffc 18176:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18177:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18178:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18179:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18180:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   18181:             if ($blocked) {
                   18182:                 my $checkrole = "cm./$cdom/$cnum";
                   18183:                 if ($env{'request.course.sec'} ne '') {
                   18184:                     $checkrole .= "/$env{'request.course.sec'}";
                   18185:                 }
                   18186:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18187:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18188:                     return;
                   18189:                 }
                   18190:             }
                   18191:         }
1.1190    musolffc 18192:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18193:                                         $env{'user.name'});
                   18194:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18195:         my $redirecturl;
1.1190    musolffc 18196:         if ($what[0]) {
                   18197: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   18198: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18199: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18200:                 return (1, $url);
1.1190    musolffc 18201:             }
1.1191    raeburn  18202:         }
                   18203:     } 
                   18204:     return ();
1.1190    musolffc 18205: }
                   18206: 
1.1174    raeburn  18207: # Use:
                   18208: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18209: #
                   18210: ##################################################
                   18211: #          password associated functions         #
                   18212: ##################################################
                   18213: sub des_keys {
                   18214:     # Make a new key for DES encryption.
                   18215:     # Each key has two parts which are returned separately.
                   18216:     # Please note:  Each key must be passed through the &hex function
                   18217:     # before it is output to the web browser.  The hex versions cannot
                   18218:     # be used to decrypt.
                   18219:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18220:                 '8','9','a','b','c','d','e','f');
                   18221:     my $lkey='';
                   18222:     for (0..7) {
                   18223:         $lkey.=$hexstr[rand(15)];
                   18224:     }
                   18225:     my $ukey='';
                   18226:     for (0..7) {
                   18227:         $ukey.=$hexstr[rand(15)];
                   18228:     }
                   18229:     return ($lkey,$ukey);
                   18230: }
                   18231: 
                   18232: sub des_decrypt {
                   18233:     my ($key,$cyphertext) = @_;
                   18234:     my $keybin=pack("H16",$key);
                   18235:     my $cypher;
                   18236:     if ($Crypt::DES::VERSION>=2.03) {
                   18237:         $cypher=new Crypt::DES $keybin;
                   18238:     } else {
                   18239:         $cypher=new DES $keybin;
                   18240:     }
1.1233    raeburn  18241:     my $plaintext='';
                   18242:     my $cypherlength = length($cyphertext);
                   18243:     my $numchunks = int($cypherlength/32);
                   18244:     for (my $j=0; $j<$numchunks; $j++) {
                   18245:         my $start = $j*32;
                   18246:         my $cypherblock = substr($cyphertext,$start,32);
                   18247:         my $chunk =
                   18248:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18249:         $chunk .=
                   18250:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18251:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18252:         $plaintext .= $chunk;
                   18253:     }
1.1174    raeburn  18254:     return $plaintext;
                   18255: }
                   18256: 
1.1344    raeburn  18257: sub get_requested_shorturls {
1.1309    raeburn  18258:     my ($cdom,$cnum,$navmap) = @_;
                   18259:     return unless (ref($navmap));
1.1344    raeburn  18260:     my ($numnew,$errors);
1.1309    raeburn  18261:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18262:     if (@toshorten) {
                   18263:         my (%maps,%resources,%titles);
                   18264:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18265:                                                                'shorturls',$cdom,$cnum);
                   18266:         if (keys(%resources)) {
1.1344    raeburn  18267:             my %tocreate;
1.1309    raeburn  18268:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18269:                 my $symb = $resources{$item};
                   18270:                 if ($symb) {
                   18271:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18272:                 }
                   18273:             }
1.1344    raeburn  18274:             if (keys(%tocreate)) {
                   18275:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18276:                                                       \%tocreate);
                   18277:             }
1.1309    raeburn  18278:         }
1.1344    raeburn  18279:     }
                   18280:     return ($numnew,$errors);
                   18281: }
                   18282: 
                   18283: sub make_short_symbs {
                   18284:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18285:     my ($numnew,@errors);
                   18286:     if (ref($tocreateref) eq 'HASH') {
                   18287:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18288:         if (keys(%tocreate)) {
                   18289:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18290:             my $su = Short::URL->new(no_vowels => 1);
                   18291:             my $init = '';
                   18292:             my (%newunique,%addcourse,%courseonly,%failed);
                   18293:             # get lock on tiny db
                   18294:             my $now = time;
1.1344    raeburn  18295:             if ($lockuser eq '') {
                   18296:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18297:             }
1.1309    raeburn  18298:             my $lockhash = {
1.1344    raeburn  18299:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18300:                             };
                   18301:             my $tries = 0;
                   18302:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18303:             my ($code,$error);
                   18304:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18305:                 $tries ++;
                   18306:                 sleep 1;
1.1319    raeburn  18307:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18308:             }
                   18309:             if ($gotlock eq 'ok') {
                   18310:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18311:                                        \%addcourse,\%courseonly,\%failed);
                   18312:                 if (keys(%failed)) {
                   18313:                     my $numfailed = scalar(keys(%failed));
                   18314:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18315:                 }
                   18316:                 if (keys(%newunique)) {
                   18317:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18318:                     if ($putres eq 'ok') {
                   18319:                         $numnew = scalar(keys(%newunique));
                   18320:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18321:                         unless ($newputres eq 'ok') {
                   18322:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18323:                         }
                   18324:                     } else {
                   18325:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18326:                     }
                   18327:                 }
                   18328:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18329:                 unless ($dellockres eq 'ok') {
                   18330:                     push(@errors,&mt('error: could not release lockfile'));
                   18331:                 }
                   18332:             } else {
                   18333:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18334:             }
                   18335:             if (keys(%courseonly)) {
                   18336:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18337:                 if ($result ne 'ok') {
                   18338:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18339:                 }
                   18340:             }
                   18341:         }
                   18342:     }
                   18343:     return ($numnew,\@errors);
                   18344: }
                   18345: 
                   18346: sub shorten_symbs {
                   18347:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18348:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18349:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18350:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18351:     my (%possibles,%collisions);
                   18352:     foreach my $key (keys(%{$tocreate})) {
                   18353:         my $num = String::CRC32::crc32($key);
                   18354:         my $tiny = $su->encode($num,$init);
                   18355:         if ($tiny) {
                   18356:             $possibles{$tiny} = $key;
                   18357:         }
                   18358:     }
                   18359:     if (!$init) {
                   18360:         $init = 1;
                   18361:     } else {
                   18362:         $init ++;
                   18363:     }
                   18364:     if (keys(%possibles)) {
                   18365:         my @posstiny = keys(%possibles);
                   18366:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18367:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18368:         if (keys(%currtiny)) {
                   18369:             foreach my $key (keys(%currtiny)) {
                   18370:                 next if ($currtiny{$key} eq '');
                   18371:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18372:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18373:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18374:                         $courseonly->{$tsymb} = $key;
                   18375:                     }
                   18376:                 } else {
                   18377:                     $collisions{$possibles{$key}} = 1;
                   18378:                 }
                   18379:                 delete($possibles{$key});
                   18380:             }
                   18381:         }
                   18382:         foreach my $key (keys(%possibles)) {
                   18383:             $newunique->{$key} = $possibles{$key};
                   18384:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18385:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18386:                 $addcourse->{$tsymb} = $key;
                   18387:             }
                   18388:         }
                   18389:     }
                   18390:     if (keys(%collisions)) {
                   18391:         if ($init <5) {
                   18392:             if (!$init) {
                   18393:                 $init = 1;
                   18394:             } else {
                   18395:                 $init ++;
                   18396:             }
                   18397:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18398:                                    $newunique,$addcourse,$courseonly,$failed);
                   18399:         } else {
                   18400:             foreach my $key (keys(%collisions)) {
                   18401:                 $failed->{$key} = 1;
                   18402:             }
                   18403:         }
                   18404:     }
                   18405:     return $init;
                   18406: }
                   18407: 
1.1328    raeburn  18408: sub is_nonframeable {
1.1329    raeburn  18409:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18410:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18411:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18412: 
                   18413:     $remprotocol = lc($remprotocol);
                   18414:     $remhost = lc($remhost);
                   18415:     my $remport = 80;
                   18416:     if ($remprotocol eq 'https') {
                   18417:         $remport = 443;
                   18418:     }
1.1330    raeburn  18419:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18420:     if ($cached) {
                   18421:         unless ($nocache) {
                   18422:             if ($result) {
                   18423:                 return 1;
                   18424:             } else {
                   18425:                 return 0;
                   18426:             }
                   18427:         }
                   18428:     }
1.1328    raeburn  18429:     my $uselink;
                   18430:     my $request = new HTTP::Request('HEAD',$url);
                   18431:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18432:     if ($response->is_success()) {
                   18433:         my $secpolicy = lc($response->header('content-security-policy'));
                   18434:         my $xframeop = lc($response->header('x-frame-options'));
                   18435:         $secpolicy =~ s/^\s+|\s+$//g;
                   18436:         $xframeop =~ s/^\s+|\s+$//g;
                   18437:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18438:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18439:             my ($origin,$protocol,$port);
                   18440:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18441:                 $port = $ENV{'SERVER_PORT'};
                   18442:             } else {
                   18443:                 $port = 80;
                   18444:             }
                   18445:             if ($absolute eq '') {
                   18446:                 $protocol = 'http:';
                   18447:                 if ($port == 443) {
                   18448:                     $protocol = 'https:';
                   18449:                 }
                   18450:                 $origin = $protocol.'//'.lc($hostname);
                   18451:             } else {
                   18452:                 $origin = lc($absolute);
                   18453:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18454:             }
                   18455:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18456:                 my $framepolicy = $1;
                   18457:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18458:                 my @policies = split(/\s+/,$framepolicy);
                   18459:                 if (@policies) {
                   18460:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18461:                         $uselink = 1;
                   18462:                     } else {
                   18463:                         $uselink = 1;
                   18464:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18465:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18466:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18467:                             undef($uselink);
                   18468:                         }
                   18469:                         if ($uselink) {
                   18470:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18471:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18472:                                     undef($uselink);
                   18473:                                 }
                   18474:                             }
                   18475:                         }
                   18476:                         if ($uselink) {
                   18477:                             my @possok;
                   18478:                             if ($ip ne '') {
                   18479:                                 push(@possok,$ip);
                   18480:                             }
                   18481:                             my $hoststr = '';
                   18482:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18483:                                 if ($hoststr eq '') {
                   18484:                                     $hoststr = $part;
                   18485:                                 } else {
                   18486:                                     $hoststr = "$part.$hoststr";
                   18487:                                 }
                   18488:                                 if ($hoststr eq $hostname) {
                   18489:                                     push(@possok,$hostname);
                   18490:                                 } else {
                   18491:                                     push(@possok,"*.$hoststr");
                   18492:                                 }
                   18493:                             }
                   18494:                             if (@possok) {
                   18495:                                 foreach my $poss (@possok) {
                   18496:                                     last if (!$uselink);
                   18497:                                     foreach my $policy (@policies) {
                   18498:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18499:                                             undef($uselink);
                   18500:                                             last;
                   18501:                                         }
                   18502:                                     }
                   18503:                                 }
                   18504:                             }
                   18505:                         }
                   18506:                     }
                   18507:                 }
                   18508:             } elsif ($xframeop ne '') {
                   18509:                 $uselink = 1;
                   18510:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18511:                 if (@policies) {
                   18512:                     unless (grep(/^deny$/,@policies)) {
                   18513:                         if ($origin ne '') {
                   18514:                             if (grep(/^sameorigin$/,@policies)) {
                   18515:                                 if ($remotehost eq $origin) {
                   18516:                                     undef($uselink);
                   18517:                                 }
                   18518:                             }
                   18519:                             if ($uselink) {
                   18520:                                 foreach my $policy (@policies) {
                   18521:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18522:                                         my $allowfrom = $1;
                   18523:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18524:                                             undef($uselink);
                   18525:                                             last;
                   18526:                                         }
                   18527:                                     }
                   18528:                                 }
                   18529:                             }
                   18530:                         }
                   18531:                     }
                   18532:                 }
                   18533:             }
                   18534:         }
                   18535:     }
1.1329    raeburn  18536:     if ($nocache) {
                   18537:         if ($cached) {
                   18538:             my $devalidate;
                   18539:             if ($uselink && !$result) {
                   18540:                 $devalidate = 1;
                   18541:             } elsif (!$uselink && $result) {
                   18542:                 $devalidate = 1;
                   18543:             }
                   18544:             if ($devalidate) {
                   18545:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18546:             }
                   18547:         }
                   18548:     } else {
                   18549:         if ($uselink) {
                   18550:             $result = 1;
                   18551:         } else {
                   18552:             $result = 0;
                   18553:         }
                   18554:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18555:     }
1.1328    raeburn  18556:     return $uselink;
                   18557: }
                   18558: 
1.112     bowersj2 18559: 1;
                   18560: __END__;
1.41      ng       18561: 

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