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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1369  ! raeburn     4: # $Id: loncommon.pm,v 1.1368 2021/10/18 22:29:20 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.1309    raeburn    89: use String::CRC32();
                     90: use Short::URL();
1.117     www        91: 
1.517     raeburn    92: # ---------------------------------------------- Designs
                     93: use vars qw(%defaultdesign);
                     94: 
1.22      www        95: my $readit;
                     96: 
1.517     raeburn    97: 
1.157     matthew    98: ##
                     99: ## Global Variables
                    100: ##
1.46      matthew   101: 
1.643     foxr      102: 
                    103: # ----------------------------------------------- SSI with retries:
                    104: #
                    105: 
                    106: =pod
                    107: 
1.648     raeburn   108: =head1 Server Side include with retries:
1.643     foxr      109: 
                    110: =over 4
                    111: 
1.648     raeburn   112: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      113: 
                    114: Performs an ssi with some number of retries.  Retries continue either
                    115: until the result is ok or until the retry count supplied by the
                    116: caller is exhausted.  
                    117: 
                    118: Inputs:
1.648     raeburn   119: 
                    120: =over 4
                    121: 
1.643     foxr      122: resource   - Identifies the resource to insert.
1.648     raeburn   123: 
1.643     foxr      124: retries    - Count of the number of retries allowed.
1.648     raeburn   125: 
1.643     foxr      126: form       - Hash that identifies the rendering options.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: Returns:
                    131: 
                    132: =over 4
                    133: 
1.643     foxr      134: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   135: 
1.643     foxr      136: response   - The response from the last attempt (which may or may not have been successful.
                    137: 
1.648     raeburn   138: =back
                    139: 
                    140: =back
                    141: 
1.643     foxr      142: =cut
                    143: 
                    144: sub ssi_with_retries {
                    145:     my ($resource, $retries, %form) = @_;
                    146: 
                    147: 
                    148:     my $ok = 0;			# True if we got a good response.
                    149:     my $content;
                    150:     my $response;
                    151: 
                    152:     # Try to get the ssi done. within the retries count:
                    153: 
                    154:     do {
                    155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    156: 	$ok      = $response->is_success;
1.650     www       157:         if (!$ok) {
                    158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    159:         }
1.643     foxr      160: 	$retries--;
                    161:     } while (!$ok && ($retries > 0));
                    162: 
                    163:     if (!$ok) {
                    164: 	$content = '';		# On error return an empty content.
                    165:     }
                    166:     return ($content, $response);
                    167: 
                    168: }
                    169: 
                    170: 
                    171: 
1.20      www       172: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  173: my %language;
1.124     www       174: my %supported_language;
1.1088    foxr      175: my %supported_codes;
1.1048    foxr      176: my %latex_language;		# For choosing hyphenation in <transl..>
                    177: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  178: my %cprtag;
1.192     taceyjo1  179: my %scprtag;
1.351     www       180: my %fe; my %fd; my %fm;
1.41      ng        181: my %category_extensions;
1.12      harris41  182: 
1.46      matthew   183: # ---------------------------------------------- Thesaurus variables
1.144     matthew   184: #
                    185: # %Keywords:
                    186: #      A hash used by &keyword to determine if a word is considered a keyword.
                    187: # $thesaurus_db_file 
                    188: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   189: 
                    190: my %Keywords;
                    191: my $thesaurus_db_file;
                    192: 
1.144     matthew   193: #
                    194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    195: # thesaurus.tab, and filecategories.tab.
                    196: #
1.18      www       197: BEGIN {
1.46      matthew   198:     # Variable initialization
                    199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    200:     #
1.22      www       201:     unless ($readit) {
1.12      harris41  202: # ------------------------------------------------------------------- languages
                    203:     {
1.158     raeburn   204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    205:                                    '/language.tab';
1.1317    raeburn   206:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  207:             while (my $line = <$fh>) {
                    208:                 next if ($line=~/^\#/);
                    209:                 chomp($line);
1.1088    foxr      210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   211:                 $language{$key}=$val.' - '.$enc;
                    212:                 if ($sup) {
                    213:                     $supported_language{$key}=$sup;
1.1088    foxr      214: 		    $supported_codes{$key}   = $code;
1.158     raeburn   215:                 }
1.1048    foxr      216: 		if ($latex) {
                    217: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      218: 		    $latex_language{$code} = $latex;
1.1048    foxr      219: 		}
1.158     raeburn   220:             }
                    221:             close($fh);
                    222:         }
1.12      harris41  223:     }
                    224: # ------------------------------------------------------------------ copyrights
                    225:     {
1.158     raeburn   226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    227:                                   '/copyright.tab';
1.1317    raeburn   228:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  229:             while (my $line = <$fh>) {
                    230:                 next if ($line=~/^\#/);
                    231:                 chomp($line);
                    232:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   233:                 $cprtag{$key}=$val;
                    234:             }
                    235:             close($fh);
                    236:         }
1.12      harris41  237:     }
1.351     www       238: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  239:     {
                    240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    241:                                   '/source_copyright.tab';
1.1317    raeburn   242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  243:             while (my $line = <$fh>) {
                    244:                 next if ($line =~ /^\#/);
                    245:                 chomp($line);
                    246:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  247:                 $scprtag{$key}=$val;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251:     }
1.63      www       252: 
1.517     raeburn   253: # -------------------------------------------------------------- default domain designs
1.63      www       254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   255:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   256:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   257:         while (my $line = <$fh>) {
                    258:             next if ($line =~ /^\#/);
                    259:             chomp($line);
                    260:             my ($key,$val)=(split(/\=/,$line));
                    261:             if ($val) { $defaultdesign{$key}=$val; }
                    262:         }
                    263:         close($fh);
1.63      www       264:     }
                    265: 
1.15      harris41  266: # ------------------------------------------------------------- file categories
                    267:     {
1.158     raeburn   268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                                   '/filecategories.tab';
1.1317    raeburn   270:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  271: 	    while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   275:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   276:             }
                    277:             close($fh);
                    278:         }
                    279: 
1.15      harris41  280:     }
1.12      harris41  281: # ------------------------------------------------------------------ file types
                    282:     {
1.158     raeburn   283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    284:                '/filetypes.tab';
1.1317    raeburn   285:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  286:             while (my $line = <$fh>) {
                    287: 		next if ($line =~ /^\#/);
                    288: 		chomp($line);
                    289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   290:                 if ($descr ne '') {
                    291:                     $fe{$ending}=lc($emb);
                    292:                     $fd{$ending}=$descr;
1.351     www       293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   294:                 }
                    295:             }
                    296:             close($fh);
                    297:         }
1.12      harris41  298:     }
1.22      www       299:     &Apache::lonnet::logthis(
1.705     tempelho  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       301:     $readit=1;
1.46      matthew   302:     }  # end of unless($readit) 
1.32      matthew   303:     
                    304: }
1.112     bowersj2  305: 
1.42      matthew   306: ###############################################################
                    307: ##           HTML and Javascript Helper Functions            ##
                    308: ###############################################################
                    309: 
                    310: =pod 
                    311: 
1.112     bowersj2  312: =head1 HTML and Javascript Functions
1.42      matthew   313: 
1.112     bowersj2  314: =over 4
                    315: 
1.648     raeburn   316: =item * &browser_and_searcher_javascript()
1.112     bowersj2  317: 
                    318: X<browsing, javascript>X<searching, javascript>Returns a string
                    319: containing javascript with two functions, C<openbrowser> and
                    320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    321: tags.
1.42      matthew   322: 
1.648     raeburn   323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   324: 
                    325: inputs: formname, elementname, only, omit
                    326: 
                    327: formname and elementname indicate the name of the html form and name of
                    328: the element that the results of the browsing selection are to be placed in. 
                    329: 
                    330: Specifying 'only' will restrict the browser to displaying only files
1.185     www       331: with the given extension.  Can be a comma separated list.
1.42      matthew   332: 
                    333: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       334: with the given extension.  Can be a comma separated list.
1.42      matthew   335: 
1.648     raeburn   336: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   337: 
                    338: Inputs: formname, elementname
                    339: 
                    340: formname and elementname specify the name of the html form and the name
                    341: of the element the selection from the search results will be placed in.
1.542     raeburn   342: 
1.42      matthew   343: =cut
                    344: 
                    345: sub browser_and_searcher_javascript {
1.199     albertel  346:     my ($mode)=@_;
                    347:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  348:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   349:     return <<END;
1.219     albertel  350: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   351:     var editbrowser = null;
1.135     albertel  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       353:         var url = '$resurl/?';
1.42      matthew   354:         if (editbrowser == null) {
                    355:             url += 'launch=1&';
                    356:         }
                    357:         url += 'catalogmode=interactive&';
1.199     albertel  358:         url += 'mode=$mode&';
1.611     albertel  359:         url += 'inhibitmenu=yes&';
1.42      matthew   360:         url += 'form=' + formname + '&';
                    361:         if (only != null) {
                    362:             url += 'only=' + only + '&';
1.217     albertel  363:         } else {
                    364:             url += 'only=&';
                    365: 	}
1.42      matthew   366:         if (omit != null) {
                    367:             url += 'omit=' + omit + '&';
1.217     albertel  368:         } else {
                    369:             url += 'omit=&';
                    370: 	}
1.135     albertel  371:         if (titleelement != null) {
                    372:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  373:         } else {
                    374: 	    url += 'titleelement=&';
                    375: 	}
1.42      matthew   376:         url += 'element=' + elementname + '';
                    377:         var title = 'Browser';
1.435     albertel  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   379:         options += ',width=700,height=600';
                    380:         editbrowser = open(url,title,options,'1');
                    381:         editbrowser.focus();
                    382:     }
                    383:     var editsearcher;
1.135     albertel  384:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   385:         var url = '/adm/searchcat?';
                    386:         if (editsearcher == null) {
                    387:             url += 'launch=1&';
                    388:         }
                    389:         url += 'catalogmode=interactive&';
1.199     albertel  390:         url += 'mode=$mode&';
1.42      matthew   391:         url += 'form=' + formname + '&';
1.135     albertel  392:         if (titleelement != null) {
                    393:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  394:         } else {
                    395: 	    url += 'titleelement=&';
                    396: 	}
1.42      matthew   397:         url += 'element=' + elementname + '';
                    398:         var title = 'Search';
1.435     albertel  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   400:         options += ',width=700,height=600';
                    401:         editsearcher = open(url,title,options,'1');
                    402:         editsearcher.focus();
                    403:     }
1.219     albertel  404: // END LON-CAPA Internal -->
1.42      matthew   405: END
1.170     www       406: }
                    407: 
                    408: sub lastresurl {
1.258     albertel  409:     if ($env{'environment.lastresurl'}) {
                    410: 	return $env{'environment.lastresurl'}
1.170     www       411:     } else {
                    412: 	return '/res';
                    413:     }
                    414: }
                    415: 
                    416: sub storeresurl {
                    417:     my $resurl=&Apache::lonnet::clutter(shift);
                    418:     unless ($resurl=~/^\/res/) { return 0; }
                    419:     $resurl=~s/\/$//;
                    420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       422:     return 1;
1.42      matthew   423: }
                    424: 
1.74      www       425: sub studentbrowser_javascript {
1.111     www       426:    unless (
1.258     albertel  427:             (($env{'request.course.id'}) && 
1.302     albertel  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    430: 					  '/'.$env{'request.course.sec'})
                    431: 	      ))
1.258     albertel  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       433:           ) { return ''; }  
1.74      www       434:    return (<<'ENDSTDBRW');
1.776     bisitz    435: <script type="text/javascript" language="Javascript">
1.824     bisitz    436: // <![CDATA[
1.74      www       437:     var stdeditbrowser;
1.1337    raeburn   438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       439:         var url = '/adm/pickstudent?';
                    440:         var filter;
1.558     albertel  441: 	if (!ignorefilter) {
                    442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    443: 	}
1.74      www       444:         if (filter != null) {
                    445:            if (filter != '') {
                    446:                url += 'filter='+filter+'&';
                    447: 	   }
                    448:         }
                    449:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       450:                                     '&udomelement='+udom+
                    451:                                     '&clicker='+clicker;
1.111     www       452: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   453:         if (courseadv == 'condition') {
                    454:             if (document.getElementById('courseadv')) {
                    455:                 courseadv = document.getElementById('courseadv').value;
                    456:             }
                    457:         }
                    458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       459:         var title = 'Student_Browser';
1.74      www       460:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    461:         options += ',width=700,height=600';
                    462:         stdeditbrowser = open(url,title,options,'1');
                    463:         stdeditbrowser.focus();
                    464:     }
1.824     bisitz    465: // ]]>
1.74      www       466: </script>
                    467: ENDSTDBRW
                    468: }
1.42      matthew   469: 
1.1003    www       470: sub resourcebrowser_javascript {
                    471:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       472:    return (<<'ENDRESBRW');
1.1003    www       473: <script type="text/javascript" language="Javascript">
                    474: // <![CDATA[
                    475:     var reseditbrowser;
1.1004    www       476:     function openresbrowser(formname,reslink) {
1.1005    www       477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       478:         var title = 'Resource_Browser';
                    479:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       480:         options += ',width=700,height=500';
1.1004    www       481:         reseditbrowser = open(url,title,options,'1');
                    482:         reseditbrowser.focus();
1.1003    www       483:     }
                    484: // ]]>
                    485: </script>
1.1004    www       486: ENDRESBRW
1.1003    www       487: }
                    488: 
1.74      www       489: sub selectstudent_link {
1.1337    raeburn   490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  494:    if ($env{'request.course.id'}) {  
1.302     albertel  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    497: 					'/'.$env{'request.course.sec'})) {
1.111     www       498: 	   return '';
                    499:        }
1.999     www       500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   501:        if ($courseadv eq 'only') {
                    502:            $callargs .= ",'',1,'$courseadv'";
                    503:        } elsif ($courseadv eq 'none') {
                    504:            $callargs .= ",'','','$courseadv'";
                    505:        } elsif ($courseadv eq 'condition') {
                    506:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   507:        }
                    508:        return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    510:               &mt('Select User').'</a></span>';
1.74      www       511:    }
1.258     albertel  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       513:        $callargs .= ",'',1"; 
1.793     raeburn   514:        return '<span class="LC_nobreak">'.
                    515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    516:               &mt('Select User').'</a></span>';
1.111     www       517:    }
                    518:    return '';
1.91      www       519: }
                    520: 
1.1004    www       521: sub selectresource_link {
                    522:    my ($form,$reslink,$arg)=@_;
                    523:    
                    524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    526:    unless ($env{'request.course.id'}) { return $arg; }
                    527:    return '<span class="LC_nobreak">'.
                    528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    529:               $arg.'</a></span>';
                    530: }
                    531: 
                    532: 
                    533: 
1.653     raeburn   534: sub authorbrowser_javascript {
                    535:     return <<"ENDAUTHORBRW";
1.776     bisitz    536: <script type="text/javascript" language="JavaScript">
1.824     bisitz    537: // <![CDATA[
1.653     raeburn   538: var stdeditbrowser;
                    539: 
                    540: function openauthorbrowser(formname,udom) {
                    541:     var url = '/adm/pickauthor?';
                    542:     url += 'form='+formname+'&roledom='+udom;
                    543:     var title = 'Author_Browser';
                    544:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    545:     options += ',width=700,height=600';
                    546:     stdeditbrowser = open(url,title,options,'1');
                    547:     stdeditbrowser.focus();
                    548: }
                    549: 
1.824     bisitz    550: // ]]>
1.653     raeburn   551: </script>
                    552: ENDAUTHORBRW
                    553: }
                    554: 
1.91      www       555: sub coursebrowser_javascript {
1.1116    raeburn   556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   557:         $credits_element,$instcode) = @_;
1.932     raeburn   558:     my $wintitle = 'Course_Browser';
1.931     raeburn   559:     if ($crstype eq 'Community') {
1.932     raeburn   560:         $wintitle = 'Community_Browser';
1.909     raeburn   561:     }
1.876     raeburn   562:     my $id_functions = &javascript_index_functions();
                    563:     my $output = '
1.776     bisitz    564: <script type="text/javascript" language="JavaScript">
1.824     bisitz    565: // <![CDATA[
1.468     raeburn   566:     var stdeditbrowser;'."\n";
1.876     raeburn   567: 
                    568:     $output .= <<"ENDSTDBRW";
1.909     raeburn   569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       570:         var url = '/adm/pickcourse?';
1.895     raeburn   571:         var formid = getFormIdByName(formname);
1.876     raeburn   572:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  573:         if (domainfilter != null) {
                    574:            if (domainfilter != '') {
                    575:                url += 'domainfilter='+domainfilter+'&';
                    576: 	   }
                    577:         }
1.91      www       578:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  579: 	                            '&cdomelement='+udom+
                    580:                                     '&cnameelement='+desc;
1.468     raeburn   581:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   582:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   583:                 url += '&roleelement='+extra_element;
                    584:                 if (domainfilter == null || domainfilter == '') {
                    585:                     url += '&domainfilter='+extra_element;
                    586:                 }
1.234     raeburn   587:             }
1.468     raeburn   588:             else {
                    589:                 if (formname == 'portform') {
                    590:                     url += '&setroles='+extra_element;
1.800     raeburn   591:                 } else {
                    592:                     if (formname == 'rules') {
                    593:                         url += '&fixeddom='+extra_element; 
                    594:                     }
1.468     raeburn   595:                 }
                    596:             }     
1.230     raeburn   597:         }
1.909     raeburn   598:         if (type != null && type != '') {
                    599:             url += '&type='+type;
                    600:         }
                    601:         if (type_elem != null && type_elem != '') {
                    602:             url += '&typeelement='+type_elem;
                    603:         }
1.872     raeburn   604:         if (formname == 'ccrs') {
                    605:             var ownername = document.forms[formid].ccuname.value;
                    606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   607:             url += '&cloner='+ownername+':'+ownerdom;
                    608:             if (type == 'Course') {
                    609:                 url += '&crscode='+document.forms[formid].crscode.value;
                    610:             }
1.1221    raeburn   611:         }
                    612:         if (formname == 'requestcrs') {
                    613:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   614:         }
1.293     raeburn   615:         if (multflag !=null && multflag != '') {
                    616:             url += '&multiple='+multflag;
                    617:         }
1.909     raeburn   618:         var title = '$wintitle';
1.91      www       619:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    620:         options += ',width=700,height=600';
                    621:         stdeditbrowser = open(url,title,options,'1');
                    622:         stdeditbrowser.focus();
                    623:     }
1.876     raeburn   624: $id_functions
                    625: ENDSTDBRW
1.1116    raeburn   626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    628:                                       $credits_element);
1.876     raeburn   629:     }
                    630:     $output .= '
                    631: // ]]>
                    632: </script>';
                    633:     return $output;
                    634: }
                    635: 
                    636: sub javascript_index_functions {
                    637:     return <<"ENDJS";
                    638: 
                    639: function getFormIdByName(formname) {
                    640:     for (var i=0;i<document.forms.length;i++) {
                    641:         if (document.forms[i].name == formname) {
                    642:             return i;
                    643:         }
                    644:     }
                    645:     return -1;
                    646: }
                    647: 
                    648: function getIndexByName(formid,item) {
                    649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    650:         if (document.forms[formid].elements[i].name == item) {
                    651:             return i;
                    652:         }
                    653:     }
                    654:     return -1;
                    655: }
1.468     raeburn   656: 
1.876     raeburn   657: function getDomainFromSelectbox(formname,udom) {
                    658:     var userdom;
                    659:     var formid = getFormIdByName(formname);
                    660:     if (formid > -1) {
                    661:         var domid = getIndexByName(formid,udom);
                    662:         if (domid > -1) {
                    663:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    665:             }
                    666:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    667:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   668:             }
                    669:         }
                    670:     }
1.876     raeburn   671:     return userdom;
                    672: }
                    673: 
                    674: ENDJS
1.468     raeburn   675: 
1.876     raeburn   676: }
                    677: 
1.1017    raeburn   678: sub javascript_array_indexof {
1.1018    raeburn   679:     return <<ENDJS;
1.1017    raeburn   680: <script type="text/javascript" language="JavaScript">
                    681: // <![CDATA[
                    682: 
                    683: if (!Array.prototype.indexOf) {
                    684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    685:         "use strict";
                    686:         if (this === void 0 || this === null) {
                    687:             throw new TypeError();
                    688:         }
                    689:         var t = Object(this);
                    690:         var len = t.length >>> 0;
                    691:         if (len === 0) {
                    692:             return -1;
                    693:         }
                    694:         var n = 0;
                    695:         if (arguments.length > 0) {
                    696:             n = Number(arguments[1]);
1.1088    foxr      697:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   698:                 n = 0;
                    699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    701:             }
                    702:         }
                    703:         if (n >= len) {
                    704:             return -1;
                    705:         }
                    706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    707:         for (; k < len; k++) {
                    708:             if (k in t && t[k] === searchElement) {
                    709:                 return k;
                    710:             }
                    711:         }
                    712:         return -1;
                    713:     }
                    714: }
                    715: 
                    716: // ]]>
                    717: </script>
                    718: 
                    719: ENDJS
                    720: 
                    721: }
                    722: 
1.876     raeburn   723: sub userbrowser_javascript {
                    724:     my $id_functions = &javascript_index_functions();
                    725:     return <<"ENDUSERBRW";
                    726: 
1.888     raeburn   727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   728:     var url = '/adm/pickuser?';
                    729:     var userdom = getDomainFromSelectbox(formname,udom);
                    730:     if (userdom != null) {
                    731:        if (userdom != '') {
                    732:            url += 'srchdom='+userdom+'&';
                    733:        }
                    734:     }
                    735:     url += 'form=' + formname + '&unameelement='+uname+
                    736:                                 '&udomelement='+udom+
                    737:                                 '&ulastelement='+ulast+
                    738:                                 '&ufirstelement='+ufirst+
                    739:                                 '&uemailelement='+uemail+
1.881     raeburn   740:                                 '&hideudomelement='+hideudom+
                    741:                                 '&coursedom='+crsdom;
1.888     raeburn   742:     if ((caller != null) && (caller != undefined)) {
                    743:         url += '&caller='+caller;
                    744:     }
1.876     raeburn   745:     var title = 'User_Browser';
                    746:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    747:     options += ',width=700,height=600';
                    748:     var stdeditbrowser = open(url,title,options,'1');
                    749:     stdeditbrowser.focus();
                    750: }
                    751: 
1.888     raeburn   752: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   753:     var formid = getFormIdByName(formname);
                    754:     if (formid > -1) {
1.888     raeburn   755:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   756:         var domid = getIndexByName(formid,udom);
                    757:         var hidedomid = getIndexByName(formid,origdom);
                    758:         if (hidedomid > -1) {
                    759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   760:             var unameval = document.forms[formid].elements[unameid].value;
                    761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    762:                 if (domid > -1) {
                    763:                     var slct = document.forms[formid].elements[domid];
                    764:                     if (slct.type == 'select-one') {
                    765:                         var i;
                    766:                         for (i=0;i<slct.length;i++) {
                    767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    768:                         }
                    769:                     }
                    770:                     if (slct.type == 'hidden') {
                    771:                         slct.value = fixeddom;
1.876     raeburn   772:                     }
                    773:                 }
1.468     raeburn   774:             }
                    775:         }
                    776:     }
1.876     raeburn   777:     return;
                    778: }
                    779: 
                    780: $id_functions
                    781: ENDUSERBRW
1.468     raeburn   782: }
                    783: 
                    784: sub setsec_javascript {
1.1116    raeburn   785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    787:         $communityrolestr);
                    788:     if ($role_element ne '') {
                    789:         my @allroles = ('st','ta','ep','in','ad');
                    790:         foreach my $crstype ('Course','Community') {
                    791:             if ($crstype eq 'Community') {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    796:             } else {
                    797:                 foreach my $role (@allroles) {
                    798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    799:                 }
                    800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    801:             }
                    802:         }
                    803:         $rolestr = '"'.join('","',@allroles).'"';
                    804:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    806:     }
1.468     raeburn   807:     my $setsections = qq|
                    808: function setSect(sectionlist) {
1.629     raeburn   809:     var sectionsArray = new Array();
                    810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    811:         sectionsArray = sectionlist.split(",");
                    812:     }
1.468     raeburn   813:     var numSections = sectionsArray.length;
                    814:     document.$formname.$sec_element.length = 0;
                    815:     if (numSections == 0) {
                    816:         document.$formname.$sec_element.multiple=false;
                    817:         document.$formname.$sec_element.size=1;
                    818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    819:     } else {
                    820:         if (numSections == 1) {
                    821:             document.$formname.$sec_element.multiple=false;
                    822:             document.$formname.$sec_element.size=1;
                    823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    826:         } else {
                    827:             for (var i=0; i<numSections; i++) {
                    828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    829:             }
                    830:             document.$formname.$sec_element.multiple=true
                    831:             if (numSections < 3) {
                    832:                 document.$formname.$sec_element.size=numSections;
                    833:             } else {
                    834:                 document.$formname.$sec_element.size=3;
                    835:             }
                    836:             document.$formname.$sec_element.options[0].selected = false
                    837:         }
                    838:     }
1.91      www       839: }
1.905     raeburn   840: 
                    841: function setRole(crstype) {
1.468     raeburn   842: |;
1.905     raeburn   843:     if ($role_element eq '') {
                    844:         $setsections .= '    return;
                    845: }
                    846: ';
                    847:     } else {
                    848:         $setsections .= qq|
                    849:     var elementLength = document.$formname.$role_element.length;
                    850:     var allroles = Array($rolestr);
                    851:     var courserolenames = Array($courserolestr);
                    852:     var communityrolenames = Array($communityrolestr);
                    853:     if (elementLength != undefined) {
                    854:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    855:             if (crstype == 'Course') {
                    856:                 return;
                    857:             } else {
                    858:                 allroles[5] = 'co';
                    859:                 for (var i=0; i<6; i++) {
                    860:                     document.$formname.$role_element.options[i].value = allroles[i];
                    861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    862:                 }
                    863:             }
                    864:         } else {
                    865:             if (crstype == 'Community') {
                    866:                 return;
                    867:             } else {
                    868:                 allroles[5] = 'cc';
                    869:                 for (var i=0; i<6; i++) {
                    870:                     document.$formname.$role_element.options[i].value = allroles[i];
                    871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    872:                 }
                    873:             }
                    874:         }
                    875:     }
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.1116    raeburn   880:     if ($credits_element) {
                    881:         $setsections .= qq|
                    882: function setCredits(defaultcredits) {
                    883:     document.$formname.$credits_element.value = defaultcredits;
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.468     raeburn   888:     return $setsections;
                    889: }
                    890: 
1.91      www       891: sub selectcourse_link {
1.909     raeburn   892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    893:        $typeelement) = @_;
                    894:    my $type = $selecttype;
1.871     raeburn   895:    my $linktext = &mt('Select Course');
                    896:    if ($selecttype eq 'Community') {
1.909     raeburn   897:        $linktext = &mt('Select Community');
1.1239    raeburn   898:    } elsif ($selecttype eq 'Placement') {
                    899:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   935:             if (!field[i].disabled) { 
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1093    raeburn   940:         if (!field.disabled) { 
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1256    raeburn   960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1256    raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1241    raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1241    raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1220    raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1015:                 push(@possibles,$id);
                   1016:             } 
1.687     raeburn  1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1256    raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1117    raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1117    raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.1088    foxr     1052: 
                   1053: =item * &list_languages()
                   1054: 
                   1055: Returns an array reference that is suitable for use in language prompters.
                   1056: Each array element is itself a two element array.  The first element
                   1057: is the language code.  The second element a descsriptiuon of the 
                   1058: language itself.  This is suitable for use in e.g.
                   1059: &Apache::edit::select_arg (once dereferenced that is).
                   1060: 
                   1061: =cut 
                   1062: 
                   1063: sub list_languages {
                   1064:     my @lang_choices;
                   1065: 
                   1066:     foreach my $id (&languageids()) {
                   1067: 	my $code = &supportedlanguagecode($id);
                   1068: 	if ($code) {
                   1069: 	    my $selector    = $supported_codes{$id};
                   1070: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1071: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1072: 	}
                   1073:     }
                   1074:     return \@lang_choices;
                   1075: }
                   1076: 
                   1077: =pod
                   1078: 
1.648     raeburn  1079: =item * &linked_select_forms(...)
1.36      matthew  1080: 
                   1081: linked_select_forms returns a string containing a <script></script> block
                   1082: and html for two <select> menus.  The select menus will be linked in that
                   1083: changing the value of the first menu will result in new values being placed
                   1084: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1085: order unless a defined order is provided.
1.36      matthew  1086: 
                   1087: linked_select_forms takes the following ordered inputs:
                   1088: 
                   1089: =over 4
                   1090: 
1.112     bowersj2 1091: =item * $formname, the name of the <form> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $firstdefault, the default value for the first menu
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1102: 
1.609     raeburn  1103: =item * $menuorder, the order of values in the first menu
                   1104: 
1.1115    raeburn  1105: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1106:         event for the first <select> tag
                   1107: 
                   1108: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1109:         event for the second <select> tag
                   1110: 
1.1245    raeburn  1111: =item * $suffix, to differentiate separate uses of select2data javascript
                   1112:         objects in a page.
                   1113: 
1.41      ng       1114: =back 
                   1115: 
1.36      matthew  1116: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1118: values for the first select menu.  The text that coincides with the 
1.41      ng       1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1120: and text for the second menu are given in the hash pointed to by 
                   1121: $menu{$choice1}->{'select2'}.  
                   1122: 
1.112     bowersj2 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1124:                        default => "B3",
                   1125:                        select2 => { 
                   1126:                            B1 => "Choice B1",
                   1127:                            B2 => "Choice B2",
                   1128:                            B3 => "Choice B3",
                   1129:                            B4 => "Choice B4"
1.609     raeburn  1130:                            },
                   1131:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1132:                    },
                   1133:                A2 => { text =>"Choice A2" ,
                   1134:                        default => "C2",
                   1135:                        select2 => { 
                   1136:                            C1 => "Choice C1",
                   1137:                            C2 => "Choice C2",
                   1138:                            C3 => "Choice C3"
1.609     raeburn  1139:                            },
                   1140:                        order => ['C2','C1','C3'],
1.112     bowersj2 1141:                    },
                   1142:                A3 => { text =>"Choice A3" ,
                   1143:                        default => "D6",
                   1144:                        select2 => { 
                   1145:                            D1 => "Choice D1",
                   1146:                            D2 => "Choice D2",
                   1147:                            D3 => "Choice D3",
                   1148:                            D4 => "Choice D4",
                   1149:                            D5 => "Choice D5",
                   1150:                            D6 => "Choice D6",
                   1151:                            D7 => "Choice D7"
1.609     raeburn  1152:                            },
                   1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1154:                    }
                   1155:                );
1.36      matthew  1156: 
                   1157: =cut
                   1158: 
                   1159: sub linked_select_forms {
                   1160:     my ($formname,
                   1161:         $middletext,
                   1162:         $firstdefault,
                   1163:         $firstselectname,
                   1164:         $secondselectname, 
1.609     raeburn  1165:         $hashref,
                   1166:         $menuorder,
1.1115    raeburn  1167:         $onchangefirst,
1.1245    raeburn  1168:         $onchangesecond,
                   1169:         $suffix
1.36      matthew  1170:         ) = @_;
                   1171:     my $second = "document.$formname.$secondselectname";
                   1172:     my $first = "document.$formname.$firstselectname";
                   1173:     # output the javascript to do the changing
                   1174:     my $result = '';
1.776     bisitz   1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1176:     $result.="// <![CDATA[\n";
1.1245    raeburn  1177:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1178:     $" = '","';
                   1179:     my $debug = '';
                   1180:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1183:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1187:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1188:         }
1.36      matthew  1189:         $result.="\"@s2values\");\n";
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1191:         my @s2texts;
                   1192:         foreach my $value (@s2values) {
1.1263    raeburn  1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1194:         }
                   1195:         $result.="\"@s2texts\");\n";
                   1196:     }
                   1197:     $"=' ';
                   1198:     $result.= <<"END";
                   1199: 
1.1245    raeburn  1200: function select1${suffix}_changed() {
1.36      matthew  1201:     // Determine new choice
1.1245    raeburn  1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1203:     // update select2
1.1245    raeburn  1204:     var values     = select2data${suffix}[newvalue].values;
                   1205:     var texts      = select2data${suffix}[newvalue].texts;
                   1206:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1207:     var i;
                   1208:     // out with the old
1.1245    raeburn  1209:     $second.options.length = 0;
                   1210:     // in with the new
1.36      matthew  1211:     for (i=0;i<values.length; i++) {
                   1212:         $second.options[i] = new Option(values[i]);
1.143     matthew  1213:         $second.options[i].value = values[i];
1.36      matthew  1214:         $second.options[i].text = texts[i];
                   1215:         if (values[i] == select2def) {
                   1216:             $second.options[i].selected = true;
                   1217:         }
                   1218:     }
                   1219: }
1.824     bisitz   1220: // ]]>
1.36      matthew  1221: </script>
                   1222: END
                   1223:     # output the initial values for the selection lists
1.1245    raeburn  1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1225:     my @order = sort(keys(%{$hashref}));
                   1226:     if (ref($menuorder) eq 'ARRAY') {
                   1227:         @order = @{$menuorder};
                   1228:     }
                   1229:     foreach my $value (@order) {
1.36      matthew  1230:         $result.="    <option value=\"$value\" ";
1.253     albertel 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1233:     }
                   1234:     $result .= "</select>\n";
                   1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1236:     $result .= $middletext;
1.1115    raeburn  1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1238:     if ($onchangesecond) {
                   1239:         $result .= ' onchange="'.$onchangesecond.'"';
                   1240:     }
                   1241:     $result .= ">\n";
1.36      matthew  1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1243:     
                   1244:     my @secondorder = sort(keys(%select2));
                   1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1247:     }
                   1248:     foreach my $value (@secondorder) {
1.36      matthew  1249:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1251:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1252:     }
                   1253:     $result .= "</select>\n";
                   1254:     #    return $debug;
                   1255:     return $result;
                   1256: }   #  end of sub linked_select_forms {
                   1257: 
1.45      matthew  1258: =pod
1.44      bowersj2 1259: 
1.973     raeburn  1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1261: 
1.112     bowersj2 1262: Returns a string corresponding to an HTML link to the given help
                   1263: $topic, where $topic corresponds to the name of a .tex file in
                   1264: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1265: spaces. 
                   1266: 
                   1267: $text will optionally be linked to the same topic, allowing you to
                   1268: link text in addition to the graphic. If you do not want to link
                   1269: text, but wish to specify one of the later parameters, pass an
                   1270: empty string. 
                   1271: 
                   1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1273: the link will not open a new window. If false, the link will open
                   1274: a new window using Javascript. (Default is false.) 
                   1275: 
                   1276: $width and $height are optional numerical parameters that will
                   1277: override the width and height of the popped up window, which may
1.973     raeburn  1278: be useful for certain help topics with big pictures included.
                   1279: 
                   1280: $imgid is the id of the img tag used for the help icon. This may be
                   1281: used in a javascript call to switch the image src.  See 
                   1282: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1283: 
                   1284: =cut
                   1285: 
                   1286: sub help_open_topic {
1.973     raeburn  1287:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1288:     $text = "" if (not defined $text);
1.44      bowersj2 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1290:     $width = 500 if (not defined $width);
1.44      bowersj2 1291:     $height = 400 if (not defined $height);
                   1292:     my $filename = $topic;
                   1293:     $filename =~ s/ /_/g;
                   1294: 
1.48      bowersj2 1295:     my $template = "";
                   1296:     my $link;
1.572     banghart 1297:     
1.159     www      1298:     $topic=~s/\W/\_/g;
1.44      bowersj2 1299: 
1.572     banghart 1300:     if (!$stayOnPage) {
1.1033    www      1301: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1302:     } elsif ($stayOnPage eq 'popup') {
                   1303:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1304:     } else {
1.48      bowersj2 1305: 	$link = "/adm/help/${filename}.hlp";
                   1306:     }
                   1307: 
                   1308:     # Add the text
1.1314    raeburn  1309:     my $target = ' target="_top"';
                   1310:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1311:         $target = '';
                   1312:     }
1.755     neumanie 1313:     if ($text ne "") {	
1.763     bisitz   1314: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1315:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1316:                   .$text.'</a>';
1.48      bowersj2 1317:     }
                   1318: 
1.763     bisitz   1319:     # (Always) Add the graphic
1.179     matthew  1320:     my $title = &mt('Online Help');
1.667     raeburn  1321:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1322:     if ($imgid ne '') {
                   1323:         $imgid = ' id="'.$imgid.'"';
                   1324:     }
1.1314    raeburn  1325:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1326:               .'<img src="'.$helpicon.'" border="0"'
                   1327:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1328:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1329:               .' /></a>';
                   1330:     if ($text ne "") {	
                   1331:         $template.='</span>';
                   1332:     }
1.44      bowersj2 1333:     return $template;
                   1334: 
1.106     bowersj2 1335: }
                   1336: 
                   1337: # This is a quicky function for Latex cheatsheet editing, since it 
                   1338: # appears in at least four places
                   1339: sub helpLatexCheatsheet {
1.1037    www      1340:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1341:     my $out;
1.106     bowersj2 1342:     my $addOther = '';
1.732     raeburn  1343:     if ($topic) {
1.1037    www      1344: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1345:     }
                   1346:     $out = '<span>' # Start cheatsheet
                   1347: 	  .$addOther
                   1348:           .'<span>'
1.1037    www      1349: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1350: 	  .'</span> <span>'
1.1037    www      1351: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1352: 	  .'</span>';
1.732     raeburn  1353:     unless ($not_author) {
1.1186    kruse    1354:         $out .= '<span>'
                   1355:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1356:                .'</span> <span>'
                   1357:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1358: 	       .'</span>';
1.732     raeburn  1359:     }
1.763     bisitz   1360:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1361:     return $out;
1.172     www      1362: }
                   1363: 
1.430     albertel 1364: sub general_help {
                   1365:     my $helptopic='Student_Intro';
                   1366:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1367: 	$helptopic='Authoring_Intro';
1.907     raeburn  1368:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1369: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1370:     } elsif ($env{'request.role'}=~/^dc/) {
                   1371:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1372:     }
                   1373:     return $helptopic;
                   1374: }
                   1375: 
                   1376: sub update_help_link {
                   1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1378:     my $origurl = $ENV{'REQUEST_URI'};
                   1379:     $origurl=~s|^/~|/priv/|;
                   1380:     my $timestamp = time;
                   1381:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1382:         $$datum = &escape($$datum);
                   1383:     }
                   1384: 
                   1385:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1386:     my $output .= <<"ENDOUTPUT";
                   1387: <script type="text/javascript">
1.824     bisitz   1388: // <![CDATA[
1.430     albertel 1389: banner_link = '$banner_link';
1.824     bisitz   1390: // ]]>
1.430     albertel 1391: </script>
                   1392: ENDOUTPUT
                   1393:     return $output;
                   1394: }
                   1395: 
                   1396: # now just updates the help link and generates a blue icon
1.193     raeburn  1397: sub help_open_menu {
1.430     albertel 1398:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1399: 	= @_;    
1.949     droeschl 1400:     $stayOnPage = 1;
1.430     albertel 1401:     my $output;
                   1402:     if ($component_help) {
                   1403: 	if (!$text) {
                   1404: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1405: 				       $width,$height);
                   1406: 	} else {
                   1407: 	    my $help_text;
                   1408: 	    $help_text=&unescape($topic);
                   1409: 	    $output='<table><tr><td>'.
                   1410: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1411: 				 $width,$height).'</td></tr></table>';
                   1412: 	}
                   1413:     }
                   1414:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1415:     return $output.$banner_link;
                   1416: }
                   1417: 
                   1418: sub top_nav_help {
1.1369  ! raeburn  1419:     my ($text,$linkattr) = @_;
1.436     albertel 1420:     $text = &mt($text);
1.949     droeschl 1421:     my $stay_on_page = 1;
                   1422: 
1.1168    raeburn  1423:     my ($link,$banner_link);
                   1424:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1425:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1426: 	                         : "javascript:helpMenu('open')";
                   1427:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1428:     }
1.201     raeburn  1429:     my $title = &mt('Get help');
1.1168    raeburn  1430:     if ($link) {
                   1431:         return <<"END";
1.436     albertel 1432: $banner_link
1.1369  ! raeburn  1433: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1434: END
1.1168    raeburn  1435:     } else {
                   1436:         return '&nbsp;'.$text.'&nbsp;';
                   1437:     }
1.436     albertel 1438: }
                   1439: 
                   1440: sub help_menu_js {
1.1154    raeburn  1441:     my ($httphost) = @_;
1.949     droeschl 1442:     my $stayOnPage = 1;
1.436     albertel 1443:     my $width = 620;
                   1444:     my $height = 600;
1.430     albertel 1445:     my $helptopic=&general_help();
1.1154    raeburn  1446:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1447:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1448:     my $start_page =
                   1449:         &Apache::loncommon::start_page('Help Menu', undef,
                   1450: 				       {'frameset'    => 1,
                   1451: 					'js_ready'    => 1,
1.1154    raeburn  1452:                                         'use_absolute' => $httphost,
1.331     albertel 1453: 					'add_entries' => {
1.1168    raeburn  1454: 					    'border' => '0', 
1.579     raeburn  1455: 					    'rows'   => "110,*",},});
1.331     albertel 1456:     my $end_page =
                   1457:         &Apache::loncommon::end_page({'frameset' => 1,
                   1458: 				      'js_ready' => 1,});
                   1459: 
1.436     albertel 1460:     my $template .= <<"ENDTEMPLATE";
                   1461: <script type="text/javascript">
1.877     bisitz   1462: // <![CDATA[
1.253     albertel 1463: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1464: var banner_link = '';
1.243     raeburn  1465: function helpMenu(target) {
                   1466:     var caller = this;
                   1467:     if (target == 'open') {
                   1468:         var newWindow = null;
                   1469:         try {
1.262     albertel 1470:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1471:         }
                   1472:         catch(error) {
                   1473:             writeHelp(caller);
                   1474:             return;
                   1475:         }
                   1476:         if (newWindow) {
                   1477:             caller = newWindow;
                   1478:         }
1.193     raeburn  1479:     }
1.243     raeburn  1480:     writeHelp(caller);
                   1481:     return;
                   1482: }
                   1483: function writeHelp(caller) {
1.1168    raeburn  1484:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1485:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1486:     caller.document.close();
                   1487:     caller.focus();
1.193     raeburn  1488: }
1.877     bisitz   1489: // END LON-CAPA Internal -->
1.253     albertel 1490: // ]]>
1.436     albertel 1491: </script>
1.193     raeburn  1492: ENDTEMPLATE
                   1493:     return $template;
                   1494: }
                   1495: 
1.172     www      1496: sub help_open_bug {
                   1497:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1498:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1499:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1500:     $text = "" if (not defined $text);
                   1501: 	$stayOnPage=1;
1.184     albertel 1502:     $width = 600 if (not defined $width);
                   1503:     $height = 600 if (not defined $height);
1.172     www      1504: 
                   1505:     $topic=~s/\W+/\+/g;
                   1506:     my $link='';
                   1507:     my $template='';
1.379     albertel 1508:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1509: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1510:     if (!$stayOnPage)
                   1511:     {
                   1512: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1513:     }
                   1514:     else
                   1515:     {
                   1516: 	$link = $url;
                   1517:     }
1.1314    raeburn  1518: 
                   1519:     my $target = ' target="_top"';
                   1520:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1521:         $target = '';
                   1522:     }
1.172     www      1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
                   1527:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1528:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('Report a Bug');
1.215     albertel 1533:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1535:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
                   1540: }
                   1541: 
                   1542: sub help_open_faq {
                   1543:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1544:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1545:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1546:     $text = "" if (not defined $text);
                   1547: 	$stayOnPage=1;
                   1548:     $width = 350 if (not defined $width);
                   1549:     $height = 400 if (not defined $height);
                   1550: 
                   1551:     $topic=~s/\W+/\+/g;
                   1552:     my $link='';
                   1553:     my $template='';
                   1554:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1555:     if (!$stayOnPage)
                   1556:     {
                   1557: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1558:     }
                   1559:     else
                   1560:     {
                   1561: 	$link = $url;
                   1562:     }
                   1563: 
                   1564:     # Add the text
                   1565:     if ($text ne "")
                   1566:     {
                   1567: 	$template .= 
1.173     www      1568:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1569:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1570:     }
                   1571: 
                   1572:     # Add the graphic
1.179     matthew  1573:     my $title = &mt('View the FAQ');
1.215     albertel 1574:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1575:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1576:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1577: ENDTEMPLATE
                   1578:     if ($text ne '') { $template.='</td></tr></table>' };
                   1579:     return $template;
                   1580: 
1.44      bowersj2 1581: }
1.37      matthew  1582: 
1.180     matthew  1583: ###############################################################
                   1584: ###############################################################
                   1585: 
1.45      matthew  1586: =pod
                   1587: 
1.648     raeburn  1588: =item * &change_content_javascript():
1.256     matthew  1589: 
                   1590: This and the next function allow you to create small sections of an
                   1591: otherwise static HTML page that you can update on the fly with
                   1592: Javascript, even in Netscape 4.
                   1593: 
                   1594: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1595: must be written to the HTML page once. It will prove the Javascript
                   1596: function "change(name, content)". Calling the change function with the
                   1597: name of the section 
                   1598: you want to update, matching the name passed to C<changable_area>, and
                   1599: the new content you want to put in there, will put the content into
                   1600: that area.
                   1601: 
                   1602: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1603: to contain room for the original contents. You need to "make space"
                   1604: for whatever changes you wish to make, and be B<sure> to check your
                   1605: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1606: it's adequate for updating a one-line status display, but little more.
                   1607: This script will set the space to 100% width, so you only need to
                   1608: worry about height in Netscape 4.
                   1609: 
                   1610: Modern browsers are much less limiting, and if you can commit to the
                   1611: user not using Netscape 4, this feature may be used freely with
                   1612: pretty much any HTML.
                   1613: 
                   1614: =cut
                   1615: 
                   1616: sub change_content_javascript {
                   1617:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1618:     if ($env{'browser.type'} eq 'netscape' &&
                   1619: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1620: 	return (<<NETSCAPE4);
                   1621: 	function change(name, content) {
                   1622: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1623: 	    doc.open();
                   1624: 	    doc.write(content);
                   1625: 	    doc.close();
                   1626: 	}
                   1627: NETSCAPE4
                   1628:     } else {
                   1629: 	# Otherwise, we need to use semi-standards-compliant code
                   1630: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1631: 	# is really scary, and every useful browser supports it
                   1632: 	return (<<DOMBASED);
                   1633: 	function change(name, content) {
                   1634: 	    element = document.getElementById(name);
                   1635: 	    element.innerHTML = content;
                   1636: 	}
                   1637: DOMBASED
                   1638:     }
                   1639: }
                   1640: 
                   1641: =pod
                   1642: 
1.648     raeburn  1643: =item * &changable_area($name,$origContent):
1.256     matthew  1644: 
                   1645: This provides a "changable area" that can be modified on the fly via
                   1646: the Javascript code provided in C<change_content_javascript>. $name is
                   1647: the name you will use to reference the area later; do not repeat the
                   1648: same name on a given HTML page more then once. $origContent is what
                   1649: the area will originally contain, which can be left blank.
                   1650: 
                   1651: =cut
                   1652: 
                   1653: sub changable_area {
                   1654:     my ($name, $origContent) = @_;
                   1655: 
1.258     albertel 1656:     if ($env{'browser.type'} eq 'netscape' &&
                   1657: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1658: 	# If this is netscape 4, we need to use the Layer tag
                   1659: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1660:     } else {
                   1661: 	return "<span id='$name'>$origContent</span>";
                   1662:     }
                   1663: }
                   1664: 
                   1665: =pod
                   1666: 
1.648     raeburn  1667: =item * &viewport_geometry_js 
1.590     raeburn  1668: 
                   1669: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: 
                   1674: sub viewport_geometry_js { 
                   1675:     return <<"GEOMETRY";
                   1676: var Geometry = {};
                   1677: function init_geometry() {
                   1678:     if (Geometry.init) { return };
                   1679:     Geometry.init=1;
                   1680:     if (window.innerHeight) {
                   1681:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1682:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1683:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1684:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1685:     }
                   1686:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1687:         Geometry.getViewportHeight =
                   1688:             function() { return document.documentElement.clientHeight; };
                   1689:         Geometry.getViewportWidth =
                   1690:             function() { return document.documentElement.clientWidth; };
                   1691: 
                   1692:         Geometry.getHorizontalScroll =
                   1693:             function() { return document.documentElement.scrollLeft; };
                   1694:         Geometry.getVerticalScroll =
                   1695:             function() { return document.documentElement.scrollTop; };
                   1696:     }
                   1697:     else if (document.body.clientHeight) {
                   1698:         Geometry.getViewportHeight =
                   1699:             function() { return document.body.clientHeight; };
                   1700:         Geometry.getViewportWidth =
                   1701:             function() { return document.body.clientWidth; };
                   1702:         Geometry.getHorizontalScroll =
                   1703:             function() { return document.body.scrollLeft; };
                   1704:         Geometry.getVerticalScroll =
                   1705:             function() { return document.body.scrollTop; };
                   1706:     }
                   1707: }
                   1708: 
                   1709: GEOMETRY
                   1710: }
                   1711: 
                   1712: =pod
                   1713: 
1.648     raeburn  1714: =item * &viewport_size_js()
1.590     raeburn  1715: 
                   1716: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1717: 
                   1718: =cut
                   1719: 
                   1720: sub viewport_size_js {
                   1721:     my $geometry = &viewport_geometry_js();
                   1722:     return <<"DIMS";
                   1723: 
                   1724: $geometry
                   1725: 
                   1726: function getViewportDims(width,height) {
                   1727:     init_geometry();
                   1728:     width.value = Geometry.getViewportWidth();
                   1729:     height.value = Geometry.getViewportHeight();
                   1730:     return;
                   1731: }
                   1732: 
                   1733: DIMS
                   1734: }
                   1735: 
                   1736: =pod
                   1737: 
1.648     raeburn  1738: =item * &resize_textarea_js()
1.565     albertel 1739: 
                   1740: emits the needed javascript to resize a textarea to be as big as possible
                   1741: 
                   1742: creates a function resize_textrea that takes two IDs first should be
                   1743: the id of the element to resize, second should be the id of a div that
                   1744: surrounds everything that comes after the textarea, this routine needs
                   1745: to be attached to the <body> for the onload and onresize events.
                   1746: 
1.648     raeburn  1747: =back
1.565     albertel 1748: 
                   1749: =cut
                   1750: 
                   1751: sub resize_textarea_js {
1.590     raeburn  1752:     my $geometry = &viewport_geometry_js();
1.565     albertel 1753:     return <<"RESIZE";
                   1754:     <script type="text/javascript">
1.824     bisitz   1755: // <![CDATA[
1.590     raeburn  1756: $geometry
1.565     albertel 1757: 
1.588     albertel 1758: function getX(element) {
                   1759:     var x = 0;
                   1760:     while (element) {
                   1761: 	x += element.offsetLeft;
                   1762: 	element = element.offsetParent;
                   1763:     }
                   1764:     return x;
                   1765: }
                   1766: function getY(element) {
                   1767:     var y = 0;
                   1768:     while (element) {
                   1769: 	y += element.offsetTop;
                   1770: 	element = element.offsetParent;
                   1771:     }
                   1772:     return y;
                   1773: }
                   1774: 
                   1775: 
1.565     albertel 1776: function resize_textarea(textarea_id,bottom_id) {
                   1777:     init_geometry();
                   1778:     var textarea        = document.getElementById(textarea_id);
                   1779:     //alert(textarea);
                   1780: 
1.588     albertel 1781:     var textarea_top    = getY(textarea);
1.565     albertel 1782:     var textarea_height = textarea.offsetHeight;
                   1783:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1784:     var bottom_top      = getY(bottom);
1.565     albertel 1785:     var bottom_height   = bottom.offsetHeight;
                   1786:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1787:     var fudge           = 23;
1.565     albertel 1788:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1789:     if (new_height < 300) {
                   1790: 	new_height = 300;
                   1791:     }
                   1792:     textarea.style.height=new_height+'px';
                   1793: }
1.824     bisitz   1794: // ]]>
1.565     albertel 1795: </script>
                   1796: RESIZE
                   1797: 
                   1798: }
                   1799: 
1.1205    golterma 1800: sub colorfuleditor_js {
1.1248    raeburn  1801:     my $browse_or_search;
                   1802:     my $respath;
                   1803:     my ($cnum,$cdom) = &crsauthor_url();
                   1804:     if ($cnum) {
                   1805:         $respath = "/res/$cdom/$cnum/";
                   1806:         my %js_lt = &Apache::lonlocal::texthash(
                   1807:             sunm => 'Sub-directory name',
                   1808:             save => 'Save page to make this permanent',
                   1809:         );
                   1810:         &js_escape(\%js_lt);
                   1811:         $browse_or_search = <<"END";
                   1812: 
                   1813:     function toggleChooser(form,element,titleid,only,search) {
                   1814:         var disp = 'none';
                   1815:         if (document.getElementById('chooser_'+element)) {
                   1816:             var curr = document.getElementById('chooser_'+element).style.display;
                   1817:             if (curr == 'none') {
                   1818:                 disp='inline';
                   1819:                 if (form.elements['chooser_'+element].length) {
                   1820:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1821:                         form.elements['chooser_'+element][i].checked = false;
                   1822:                     }
                   1823:                 }
                   1824:                 toggleResImport(form,element);
                   1825:             }
                   1826:             document.getElementById('chooser_'+element).style.display = disp;
                   1827:         }
                   1828:     }
                   1829: 
                   1830:     function toggleCrsFile(form,element,numdirs) {
                   1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1832:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1833:             if (curr == 'none') {
                   1834:                 if (numdirs) {
                   1835:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1836:                     if (numdirs > 1) {
                   1837:                         window['select1'+element+'_changed']();
                   1838:                     }
                   1839:                 }
                   1840:             } 
                   1841:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1842:             
                   1843:         }
                   1844:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1845:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1846:             if (document.getElementById('uploadcrsres_'+element)) {
                   1847:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1848:             }
                   1849:         }
                   1850:         return;
                   1851:     }
                   1852: 
                   1853:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1854:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1855:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1856:         }
                   1857:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1858:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1859:             if (curr == 'none') {
                   1860:                 if (numcrsdirs) {
                   1861:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1862:                    form.elements['newsubdir_'+element][0].checked = true;
                   1863:                    toggleNewsubdir(form,element);
                   1864:                 }
                   1865:             }
                   1866:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1867:         }
                   1868:         return;
                   1869:     }
                   1870: 
                   1871:     function toggleResImport(form,element) {
                   1872:         var choices = new Array('crsres','upload');
                   1873:         for (var i=0; i<choices.length; i++) {
                   1874:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1875:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1876:             }
                   1877:         }
                   1878:     }
                   1879: 
                   1880:     function toggleNewsubdir(form,element) {
                   1881:         var newsub = form.elements['newsubdir_'+element];
                   1882:         if (newsub) {
                   1883:             if (newsub.length) {
                   1884:                 for (var j=0; j<newsub.length; j++) {
                   1885:                     if (newsub[j].checked) {
                   1886:                         if (document.getElementById('newsubdirname_'+element)) {
                   1887:                             if (newsub[j].value == '1') {
                   1888:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1889:                                 if (document.getElementById('newsubdir_'+element)) {
                   1890:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1891:                                 }
                   1892:                             } else {
                   1893:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1894:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1895:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1896:                             }
                   1897:                         }
                   1898:                         break; 
                   1899:                     }
                   1900:                 }
                   1901:             }
                   1902:         }
                   1903:     }
                   1904: 
                   1905:     function updateCrsFile(form,element) {
                   1906:         var directory = form.elements['coursepath_'+element];
                   1907:         var filename = form.elements['coursefile_'+element];
                   1908:         var path = directory.options[directory.selectedIndex].value;
                   1909:         var file = filename.options[filename.selectedIndex].value;
                   1910:         form.elements[element].value = '$respath';
                   1911:         if (path == '/') {
                   1912:             form.elements[element].value += file;
                   1913:         } else {
                   1914:             form.elements[element].value += path+'/'+file;
                   1915:         }
                   1916:         unClean();
                   1917:         if (document.getElementById('previewimg_'+element)) {
                   1918:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1919:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1920:         }
                   1921:         if (document.getElementById('showimg_'+element)) {
                   1922:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1923:         }
                   1924:         toggleChooser(form,element);
                   1925:         return;
                   1926:     }
                   1927: 
                   1928:     function uploadDone(suffix,name) {
                   1929:         if (name) {
                   1930: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1931:             unClean();
                   1932:             toggleChooser(document.forms["lonhomework"],suffix);
                   1933:         }
                   1934:     }
                   1935: 
                   1936: \$(document).ready(function(){
                   1937: 
                   1938:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1939:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1940:             var buttonId = this.id;
                   1941:             var suffix = buttonId.toString();
                   1942:             suffix = suffix.replace(/^crsupload_/,'');
                   1943:             event.preventDefault();
                   1944:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1945:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1946:             \$(this.form).submit();
                   1947:             document.lonhomework.target = '';
                   1948:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1949:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1950:             }
                   1951:             return false;
                   1952:         }
                   1953:     });
                   1954: });
                   1955: END
                   1956:     }
1.1205    golterma 1957:     return <<"COLORFULEDIT"
                   1958: <script type="text/javascript">
                   1959: // <![CDATA[>
                   1960:     function fold_box(curDepth, lastresource){
                   1961: 
                   1962:     // we need a list because there can be several blocks you need to fold in one tag
                   1963:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1964:     // but there is only one folding button per tag
                   1965:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1966: 
                   1967:         if(block.item(0).style.display == 'none'){
                   1968: 
                   1969:             foldbutton.value = '@{[&mt("Hide")]}';
                   1970:             for (i = 0; i < block.length; i++){
                   1971:                 block.item(i).style.display = '';
                   1972:             }
                   1973:         }else{
                   1974: 
                   1975:             foldbutton.value = '@{[&mt("Show")]}';
                   1976:             for (i = 0; i < block.length; i++){
                   1977:                 // block.item(i).style.visibility = 'collapse';
                   1978:                 block.item(i).style.display = 'none';
                   1979:             }
                   1980:         };
                   1981:         saveState(lastresource);
                   1982:     }
                   1983: 
                   1984:     function saveState (lastresource) {
                   1985: 
                   1986:         var tag_list = getTagList();
                   1987:         if(tag_list != null){
                   1988:             var timestamp = new Date().getTime();
                   1989:             var key = lastresource;
                   1990: 
                   1991:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1992:             // starting with timestamp
                   1993:             var value = timestamp+';';
                   1994: 
                   1995:             // building the list of key-value pairs
                   1996:             for(var i = 0; i < tag_list.length; i++){
                   1997:                 value += tag_list[i]+',';
                   1998:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1999:             }
                   2000: 
                   2001:             // only iterate whole storage if nothing to override
                   2002:             if(localStorage.getItem(key) == null){        
                   2003: 
                   2004:                 // prevent storage from growing large
                   2005:                 if(localStorage.length > 50){
                   2006:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2007:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2008:                     var oldest_key;
                   2009:                     
                   2010:                     for(var i = 1; i < localStorage.length; i++){
                   2011:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2012:                             oldest_key = localStorage.key(i);
                   2013:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2014:                         }
                   2015:                     }
                   2016:                     localStorage.removeItem(oldest_key);
                   2017:                 }
                   2018:             }
                   2019:             localStorage.setItem(key,value);
                   2020:         }
                   2021:     }
                   2022: 
                   2023:     // restore folding status of blocks (on page load)
                   2024:     function restoreState (lastresource) {
                   2025:         if(localStorage.getItem(lastresource) != null){
                   2026:             var key = lastresource;
                   2027:             var value = localStorage.getItem(key);
                   2028:             var regex_delTimestamp = /^\d+;/;
                   2029: 
                   2030:             value.replace(regex_delTimestamp, '');
                   2031: 
                   2032:             var valueArr = value.split(';');
                   2033:             var pairs;
                   2034:             var elements;
                   2035:             for (var i = 0; i < valueArr.length; i++){
                   2036:                 pairs = valueArr[i].split(',');
                   2037:                 elements = document.getElementsByName(pairs[0]);
                   2038: 
                   2039:                 for (var j = 0; j < elements.length; j++){  
                   2040:                     elements[j].style.display = pairs[1];
                   2041:                     if (pairs[1] == "none"){
                   2042:                         var regex_id = /([_\\d]+)\$/;
                   2043:                         regex_id.exec(pairs[0]);
                   2044:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2045:                     }
                   2046:                 }
                   2047:             }
                   2048:         }
                   2049:     }
                   2050: 
                   2051:     function getTagList () {
                   2052:         
                   2053:         var stringToSearch = document.lonhomework.innerHTML;
                   2054: 
                   2055:         var ret = new Array();
                   2056:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2057:         var tag_list = stringToSearch.match(regex_findBlock);
                   2058: 
                   2059:         if(tag_list != null){
                   2060:             for(var i = 0; i < tag_list.length; i++){            
                   2061:                 ret.push(tag_list[i].replace(/"/, ''));
                   2062:             }
                   2063:         }
                   2064:         return ret;
                   2065:     }
                   2066: 
                   2067:     function saveScrollPosition (resource) {
                   2068:         var tag_list = getTagList();
                   2069: 
                   2070:         // we dont always want to jump to the first block
                   2071:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2072:         if(\$(window).scrollTop() > 170){
                   2073:             if(tag_list != null){
                   2074:                 var result;
                   2075:                 for(var i = 0; i < tag_list.length; i++){
                   2076:                     if(isElementInViewport(tag_list[i])){
                   2077:                         result += tag_list[i]+';';
                   2078:                     }
                   2079:                 }
                   2080:                 sessionStorage.setItem('anchor_'+resource, result);
                   2081:             }
                   2082:         } else {
                   2083:             // we dont need to save zero, just delete the item to leave everything tidy
                   2084:             sessionStorage.removeItem('anchor_'+resource);
                   2085:         }
                   2086:     }
                   2087: 
                   2088:     function restoreScrollPosition(resource){
                   2089: 
                   2090:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2091:         if(elem != null){
                   2092:             var tag_list = elem.split(';');
                   2093:             var elem_list;
                   2094: 
                   2095:             for(var i = 0; i < tag_list.length; i++){
                   2096:                 elem_list = document.getElementsByName(tag_list[i]);
                   2097:                 
                   2098:                 if(elem_list.length > 0){
                   2099:                     elem = elem_list[0];
                   2100:                     break;
                   2101:                 }
                   2102:             }
                   2103:             elem.scrollIntoView();
                   2104:         }
                   2105:     }
                   2106: 
                   2107:     function isElementInViewport(el) {
                   2108: 
                   2109:         // change to last element instead of first
                   2110:         var elem = document.getElementsByName(el);
                   2111:         var rect = elem[0].getBoundingClientRect();
                   2112: 
                   2113:         return (
                   2114:             rect.top >= 0 &&
                   2115:             rect.left >= 0 &&
                   2116:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2117:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2118:         );
                   2119:     }
                   2120:     
                   2121:     function autosize(depth){
                   2122:         var cmInst = window['cm'+depth];
                   2123:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2124: 
                   2125:         // is fixed size, switching to dynamic
                   2126:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2127:             cmInst.setSize("","auto");
                   2128:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2129:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2130: 
                   2131:         // is dynamic size, switching to fixed
                   2132:         } else {
                   2133:             cmInst.setSize("","300px");
                   2134:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2135:             sessionStorage.removeItem("autosized_"+depth);
                   2136:         }
                   2137:     }
                   2138: 
1.1248    raeburn  2139: $browse_or_search
1.1205    golterma 2140: 
                   2141: // ]]>
                   2142: </script>
                   2143: COLORFULEDIT
                   2144: }
                   2145: 
                   2146: sub xmleditor_js {
                   2147:     return <<XMLEDIT
                   2148: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2149: <script type="text/javascript">
                   2150: // <![CDATA[>
                   2151: 
                   2152:     function saveScrollPosition (resource) {
                   2153: 
                   2154:         var scrollPos = \$(window).scrollTop();
                   2155:         sessionStorage.setItem(resource,scrollPos);
                   2156:     }
                   2157: 
                   2158:     function restoreScrollPosition(resource){
                   2159: 
                   2160:         var scrollPos = sessionStorage.getItem(resource);
                   2161:         \$(window).scrollTop(scrollPos);
                   2162:     }
                   2163: 
                   2164:     // unless internet explorer
                   2165:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2166: 
                   2167:         \$(document).ready(function() {
                   2168:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2169:         });
                   2170:     }
                   2171: 
                   2172:     // inserts text at cursor position into codemirror (xml editor only)
                   2173:     function insertText(text){
                   2174:         cm.focus();
                   2175:         var curPos = cm.getCursor();
                   2176:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2177:     }
                   2178: // ]]>
                   2179: </script>
                   2180: XMLEDIT
                   2181: }
                   2182: 
                   2183: sub insert_folding_button {
                   2184:     my $curDepth = $Apache::lonxml::curdepth;
                   2185:     my $lastresource = $env{'request.ambiguous'};
                   2186: 
                   2187:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2188:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2189: }
                   2190: 
1.1248    raeburn  2191: sub crsauthor_url {
                   2192:     my ($url) = @_;
                   2193:     if ($url eq '') {
                   2194:         $url = $ENV{'REQUEST_URI'};
                   2195:     }
                   2196:     my ($cnum,$cdom);
                   2197:     if ($env{'request.course.id'}) {
                   2198:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2199:         if ($audom ne '' && $auname ne '') {
                   2200:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2201:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2202:                 $cnum = $auname;
                   2203:                 $cdom = $audom;
                   2204:             }
                   2205:         }
                   2206:     }
                   2207:     return ($cnum,$cdom);
                   2208: }
                   2209: 
                   2210: sub import_crsauthor_form {
1.1265    raeburn  2211:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2212:     return (0) unless ($env{'request.course.id'});
                   2213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2215:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2216:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2217:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2218:     my @ids=&Apache::lonnet::current_machine_ids();
                   2219:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2220:     
                   2221:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2222:         $is_home = 1;
                   2223:     }
                   2224:     $relpath = "/priv/$cdom/$cnum";
                   2225:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2226:     my %lt = &Apache::lonlocal::texthash (
                   2227:         fnam => 'Filename',
                   2228:         dire => 'Directory',
                   2229:     );
                   2230:     my $numdirs = scalar(keys(%files));
                   2231:     my (%possexts,$singledir,@singledirfiles);
                   2232:     if ($only) {
                   2233:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2234:     }
                   2235:     my (%nonemptydirs,$possdirs);
                   2236:     if ($numdirs > 1) {
                   2237:         my @order;
                   2238:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2239:             if (ref($files{$key}) eq 'HASH') {
                   2240:                 my $shown = $key;
                   2241:                 if ($key eq '') {
                   2242:                     $shown = '/';
                   2243:                 }
                   2244:                 my @ordered = ();
                   2245:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2246:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2247:                     if ($only) {
                   2248:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2249:                         unless ($possexts{lc($ext)}) {
                   2250:                             next;
                   2251:                         }
                   2252:                     }
                   2253:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2254:                     push(@ordered,$file);
                   2255:                 }
                   2256:                 if (@ordered) {
                   2257:                     push(@order,$key);
                   2258:                     $nonemptydirs{$key} = 1;
                   2259:                     $selimport_menus{$key}->{'text'} = $shown;
                   2260:                     $selimport_menus{$key}->{'default'} = '';
                   2261:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2262:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2263:                 }
                   2264:             }
                   2265:         }
                   2266:         $possdirs = scalar(keys(%nonemptydirs));
                   2267:         if ($possdirs > 1) {
                   2268:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2269:             $output = $lt{'dire'}.
                   2270:                       &linked_select_forms($form,'<br />'.
                   2271:                                            $lt{'fnam'},'',
                   2272:                                            $firstselectname,$secondselectname,
                   2273:                                            \%selimport_menus,\@order,
                   2274:                                            $onchangefirst,'',$suffix).'<br />';
                   2275:         } elsif ($possdirs == 1) {
                   2276:             $singledir = (keys(%nonemptydirs))[0];
                   2277:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2278:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2279:             }
                   2280:             delete($selimport_menus{$singledir});
                   2281:         }
                   2282:     } elsif ($numdirs == 1) {
                   2283:         $singledir = (keys(%files))[0];
                   2284:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2285:             if ($only) {
                   2286:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2287:                 unless ($possexts{lc($ext)}) {
                   2288:                     next;
                   2289:                 }
1.1315    raeburn  2290:             } else {
                   2291:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2292:             }
                   2293:             push(@singledirfiles,$file);
                   2294:         }
                   2295:         if (@singledirfiles) {
1.1315    raeburn  2296:             $possdirs = 1;
1.1248    raeburn  2297:         }
                   2298:     }
                   2299:     if (($possdirs == 1) && (@singledirfiles)) {
                   2300:         my $showdir = $singledir;
                   2301:         if ($singledir eq '') {
                   2302:             $showdir = '/';
                   2303:         }
                   2304:         $output = $lt{'dire'}.
                   2305:                   '<select name="'.$firstselectname.'">'.
                   2306:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2307:                   '</select><br />'.
                   2308:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2309:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2310:         foreach my $file (@singledirfiles) {
                   2311:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2312:         }
                   2313:         $output .= '</select><br />'."\n";
                   2314:     }
                   2315:     return ($possdirs,$output);
                   2316: }
                   2317: 
1.565     albertel 2318: =pod
                   2319: 
1.256     matthew  2320: =head1 Excel and CSV file utility routines
                   2321: 
                   2322: =cut
                   2323: 
                   2324: ###############################################################
                   2325: ###############################################################
                   2326: 
                   2327: =pod
                   2328: 
1.1162    raeburn  2329: =over 4
                   2330: 
1.648     raeburn  2331: =item * &csv_translate($text) 
1.37      matthew  2332: 
1.185     www      2333: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2334: format.
                   2335: 
                   2336: =cut
                   2337: 
1.180     matthew  2338: ###############################################################
                   2339: ###############################################################
1.37      matthew  2340: sub csv_translate {
                   2341:     my $text = shift;
                   2342:     $text =~ s/\"/\"\"/g;
1.209     albertel 2343:     $text =~ s/\n/ /g;
1.37      matthew  2344:     return $text;
                   2345: }
1.180     matthew  2346: 
                   2347: ###############################################################
                   2348: ###############################################################
                   2349: 
                   2350: =pod
                   2351: 
1.648     raeburn  2352: =item * &define_excel_formats()
1.180     matthew  2353: 
                   2354: Define some commonly used Excel cell formats.
                   2355: 
                   2356: Currently supported formats:
                   2357: 
                   2358: =over 4
                   2359: 
                   2360: =item header
                   2361: 
                   2362: =item bold
                   2363: 
                   2364: =item h1
                   2365: 
                   2366: =item h2
                   2367: 
                   2368: =item h3
                   2369: 
1.256     matthew  2370: =item h4
                   2371: 
                   2372: =item i
                   2373: 
1.180     matthew  2374: =item date
                   2375: 
                   2376: =back
                   2377: 
                   2378: Inputs: $workbook
                   2379: 
                   2380: Returns: $format, a hash reference.
                   2381: 
1.1057    foxr     2382: 
1.180     matthew  2383: =cut
                   2384: 
                   2385: ###############################################################
                   2386: ###############################################################
                   2387: sub define_excel_formats {
                   2388:     my ($workbook) = @_;
                   2389:     my $format;
                   2390:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2391:                                                 bottom    => 1,
                   2392:                                                 align     => 'center');
                   2393:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2394:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2395:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2396:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2397:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2398:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2399:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2400:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2401:     return $format;
                   2402: }
                   2403: 
                   2404: ###############################################################
                   2405: ###############################################################
1.113     bowersj2 2406: 
                   2407: =pod
                   2408: 
1.648     raeburn  2409: =item * &create_workbook()
1.255     matthew  2410: 
                   2411: Create an Excel worksheet.  If it fails, output message on the
                   2412: request object and return undefs.
                   2413: 
                   2414: Inputs: Apache request object
                   2415: 
                   2416: Returns (undef) on failure, 
                   2417:     Excel worksheet object, scalar with filename, and formats 
                   2418:     from &Apache::loncommon::define_excel_formats on success
                   2419: 
                   2420: =cut
                   2421: 
                   2422: ###############################################################
                   2423: ###############################################################
                   2424: sub create_workbook {
                   2425:     my ($r) = @_;
                   2426:         #
                   2427:     # Create the excel spreadsheet
                   2428:     my $filename = '/prtspool/'.
1.258     albertel 2429:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2430:         time.'_'.rand(1000000000).'.xls';
                   2431:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2432:     if (! defined($workbook)) {
                   2433:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2434:         $r->print(
                   2435:             '<p class="LC_error">'
                   2436:            .&mt('Problems occurred in creating the new Excel file.')
                   2437:            .' '.&mt('This error has been logged.')
                   2438:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2439:            .'</p>'
                   2440:         );
1.255     matthew  2441:         return (undef);
                   2442:     }
                   2443:     #
1.1014    foxr     2444:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2445:     #
                   2446:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2447:     return ($workbook,$filename,$format);
                   2448: }
                   2449: 
                   2450: ###############################################################
                   2451: ###############################################################
                   2452: 
                   2453: =pod
                   2454: 
1.648     raeburn  2455: =item * &create_text_file()
1.113     bowersj2 2456: 
1.542     raeburn  2457: Create a file to write to and eventually make available to the user.
1.256     matthew  2458: If file creation fails, outputs an error message on the request object and 
                   2459: return undefs.
1.113     bowersj2 2460: 
1.256     matthew  2461: Inputs: Apache request object, and file suffix
1.113     bowersj2 2462: 
1.256     matthew  2463: Returns (undef) on failure, 
                   2464:     Filehandle and filename on success.
1.113     bowersj2 2465: 
                   2466: =cut
                   2467: 
1.256     matthew  2468: ###############################################################
                   2469: ###############################################################
                   2470: sub create_text_file {
                   2471:     my ($r,$suffix) = @_;
                   2472:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2473:     my $fh;
                   2474:     my $filename = '/prtspool/'.
1.258     albertel 2475:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2476:         time.'_'.rand(1000000000).'.'.$suffix;
                   2477:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2478:     if (! defined($fh)) {
                   2479:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2480:         $r->print(
                   2481:             '<p class="LC_error">'
                   2482:            .&mt('Problems occurred in creating the output file.')
                   2483:            .' '.&mt('This error has been logged.')
                   2484:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2485:            .'</p>'
                   2486:         );
1.113     bowersj2 2487:     }
1.256     matthew  2488:     return ($fh,$filename)
1.113     bowersj2 2489: }
                   2490: 
                   2491: 
1.256     matthew  2492: =pod 
1.113     bowersj2 2493: 
                   2494: =back
                   2495: 
                   2496: =cut
1.37      matthew  2497: 
                   2498: ###############################################################
1.33      matthew  2499: ##        Home server <option> list generating code          ##
                   2500: ###############################################################
1.35      matthew  2501: 
1.169     www      2502: # ------------------------------------------
                   2503: 
                   2504: sub domain_select {
1.1289    raeburn  2505:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2506:     my @possdoms;
                   2507:     if (ref($incdoms) eq 'ARRAY') {
                   2508:         @possdoms = @{$incdoms};
                   2509:     } else {
                   2510:         @possdoms = &Apache::lonnet::all_domains();
                   2511:     }
                   2512: 
1.169     www      2513:     my %domains=map { 
1.514     albertel 2514: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2515:     } @possdoms;
                   2516: 
                   2517:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2518:         foreach my $dom (@{$excdoms}) {
                   2519:             delete($domains{$dom});
                   2520:         }
                   2521:     }
                   2522: 
1.169     www      2523:     if ($multiple) {
                   2524: 	$domains{''}=&mt('Any domain');
1.550     albertel 2525: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2526: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2527:     } else {
1.550     albertel 2528: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2529: 	return &select_form($name,$value,\%domains);
1.169     www      2530:     }
                   2531: }
                   2532: 
1.282     albertel 2533: #-------------------------------------------
                   2534: 
                   2535: =pod
                   2536: 
1.519     raeburn  2537: =head1 Routines for form select boxes
                   2538: 
                   2539: =over 4
                   2540: 
1.648     raeburn  2541: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2542: 
                   2543: Returns a string containing a <select> element int multiple mode
                   2544: 
                   2545: 
                   2546: Args:
                   2547:   $name - name of the <select> element
1.506     raeburn  2548:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2549:   $size - number of rows long the select element is
1.283     albertel 2550:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2551:           (shown text should already have been &mt())
1.506     raeburn  2552:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2553: 
1.282     albertel 2554: =cut
                   2555: 
                   2556: #-------------------------------------------
1.169     www      2557: sub multiple_select_form {
1.284     albertel 2558:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2559:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2560:     my $output='';
1.191     matthew  2561:     if (! defined($size)) {
                   2562:         $size = 4;
1.283     albertel 2563:         if (scalar(keys(%$hash))<4) {
                   2564:             $size = scalar(keys(%$hash));
1.191     matthew  2565:         }
                   2566:     }
1.734     bisitz   2567:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2568:     my @order;
1.506     raeburn  2569:     if (ref($order) eq 'ARRAY')  {
                   2570:         @order = @{$order};
                   2571:     } else {
                   2572:         @order = sort(keys(%$hash));
1.501     banghart 2573:     }
                   2574:     if (exists($$hash{'select_form_order'})) {
                   2575:         @order = @{$$hash{'select_form_order'}};
                   2576:     }
                   2577:         
1.284     albertel 2578:     foreach my $key (@order) {
1.356     albertel 2579:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2580:         $output.='selected="selected" ' if ($selected{$key});
                   2581:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2582:     }
                   2583:     $output.="</select>\n";
                   2584:     return $output;
                   2585: }
                   2586: 
1.88      www      2587: #-------------------------------------------
                   2588: 
                   2589: =pod
                   2590: 
1.1254    raeburn  2591: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2592: 
                   2593: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2594: allow a user to select options from a ref to a hash containing:
                   2595: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2596: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2597: An optional arg -- $readonly -- if true will cause the select form
                   2598: to be disabled, e.g., for the case where an instructor has a section-
                   2599: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2600: 
1.88      www      2601: See lonrights.pm for an example invocation and use.
                   2602: 
                   2603: =cut
                   2604: 
                   2605: #-------------------------------------------
                   2606: sub select_form {
1.1228    raeburn  2607:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2608:     return unless (ref($hashref) eq 'HASH');
                   2609:     if ($onchange) {
                   2610:         $onchange = ' onchange="'.$onchange.'"';
                   2611:     }
1.1228    raeburn  2612:     my $disabled;
                   2613:     if ($readonly) {
                   2614:         $disabled = ' disabled="disabled"';
                   2615:     }
                   2616:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2617:     my @keys;
1.970     raeburn  2618:     if (exists($hashref->{'select_form_order'})) {
                   2619: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2620:     } else {
1.970     raeburn  2621: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2622:     }
1.356     albertel 2623:     foreach my $key (@keys) {
                   2624:         $selectform.=
                   2625: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2626:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2627:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2628:     }
                   2629:     $selectform.="</select>";
                   2630:     return $selectform;
                   2631: }
                   2632: 
1.475     www      2633: # For display filters
                   2634: 
                   2635: sub display_filter {
1.1074    raeburn  2636:     my ($context) = @_;
1.475     www      2637:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2638:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2639:     my $phraseinput = 'hidden';
                   2640:     my $includeinput = 'hidden';
                   2641:     my ($checked,$includetypestext);
                   2642:     if ($env{'form.displayfilter'} eq 'containing') {
                   2643:         $phraseinput = 'text'; 
                   2644:         if ($context eq 'parmslog') {
                   2645:             $includeinput = 'checkbox';
                   2646:             if ($env{'form.includetypes'}) {
                   2647:                 $checked = ' checked="checked"';
                   2648:             }
                   2649:             $includetypestext = &mt('Include parameter types');
                   2650:         }
                   2651:     } else {
                   2652:         $includetypestext = '&nbsp;';
                   2653:     }
                   2654:     my ($additional,$secondid,$thirdid);
                   2655:     if ($context eq 'parmslog') {
                   2656:         $additional = 
                   2657:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2658:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2659:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2660:             '</label>';
                   2661:         $secondid = 'includetypes';
                   2662:         $thirdid = 'includetypestext';
                   2663:     }
                   2664:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2665:                                                     '$secondid','$thirdid')";
                   2666:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2667: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2668: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2669: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2670:            &mt('Filter: [_1]',
1.477     www      2671: 	   &select_form($env{'form.displayfilter'},
                   2672: 			'displayfilter',
1.970     raeburn  2673: 			{'currentfolder' => 'Current folder/page',
1.477     www      2674: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2675: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2676: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2677:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2678:                          '" />'.$additional;
                   2679: }
                   2680: 
                   2681: sub display_filter_js {
                   2682:     my $includetext = &mt('Include parameter types');
                   2683:     return <<"ENDJS";
                   2684:   
                   2685: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2686:     var firstType = 'hidden';
                   2687:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2688:         firstType = 'text';
                   2689:     }
                   2690:     firstObject = document.getElementById(firstid);
                   2691:     if (typeof(firstObject) == 'object') {
                   2692:         if (firstObject.type != firstType) {
                   2693:             changeInputType(firstObject,firstType);
                   2694:         }
                   2695:     }
                   2696:     if (context == 'parmslog') {
                   2697:         var secondType = 'hidden';
                   2698:         if (firstType == 'text') {
                   2699:             secondType = 'checkbox';
                   2700:         }
                   2701:         secondObject = document.getElementById(secondid);  
                   2702:         if (typeof(secondObject) == 'object') {
                   2703:             if (secondObject.type != secondType) {
                   2704:                 changeInputType(secondObject,secondType);
                   2705:             }
                   2706:         }
                   2707:         var textItem = document.getElementById(thirdid);
                   2708:         var currtext = textItem.innerHTML;
                   2709:         var newtext;
                   2710:         if (firstType == 'text') {
                   2711:             newtext = '$includetext';
                   2712:         } else {
                   2713:             newtext = '&nbsp;';
                   2714:         }
                   2715:         if (currtext != newtext) {
                   2716:             textItem.innerHTML = newtext;
                   2717:         }
                   2718:     }
                   2719:     return;
                   2720: }
                   2721: 
                   2722: function changeInputType(oldObject,newType) {
                   2723:     var newObject = document.createElement('input');
                   2724:     newObject.type = newType;
                   2725:     if (oldObject.size) {
                   2726:         newObject.size = oldObject.size;
                   2727:     }
                   2728:     if (oldObject.value) {
                   2729:         newObject.value = oldObject.value;
                   2730:     }
                   2731:     if (oldObject.name) {
                   2732:         newObject.name = oldObject.name;
                   2733:     }
                   2734:     if (oldObject.id) {
                   2735:         newObject.id = oldObject.id;
                   2736:     }
                   2737:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2738:     return;
                   2739: }
                   2740: 
                   2741: ENDJS
1.475     www      2742: }
                   2743: 
1.167     www      2744: sub gradeleveldescription {
                   2745:     my $gradelevel=shift;
                   2746:     my %gradelevels=(0 => 'Not specified',
                   2747: 		     1 => 'Grade 1',
                   2748: 		     2 => 'Grade 2',
                   2749: 		     3 => 'Grade 3',
                   2750: 		     4 => 'Grade 4',
                   2751: 		     5 => 'Grade 5',
                   2752: 		     6 => 'Grade 6',
                   2753: 		     7 => 'Grade 7',
                   2754: 		     8 => 'Grade 8',
                   2755: 		     9 => 'Grade 9',
                   2756: 		     10 => 'Grade 10',
                   2757: 		     11 => 'Grade 11',
                   2758: 		     12 => 'Grade 12',
                   2759: 		     13 => 'Grade 13',
                   2760: 		     14 => '100 Level',
                   2761: 		     15 => '200 Level',
                   2762: 		     16 => '300 Level',
                   2763: 		     17 => '400 Level',
                   2764: 		     18 => 'Graduate Level');
                   2765:     return &mt($gradelevels{$gradelevel});
                   2766: }
                   2767: 
1.163     www      2768: sub select_level_form {
                   2769:     my ($deflevel,$name)=@_;
                   2770:     unless ($deflevel) { $deflevel=0; }
1.167     www      2771:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2772:     for (my $i=0; $i<=18; $i++) {
                   2773:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2774:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2775:                 ">".&gradeleveldescription($i)."</option>\n";
                   2776:     }
                   2777:     $selectform.="</select>";
                   2778:     return $selectform;
1.163     www      2779: }
1.167     www      2780: 
1.35      matthew  2781: #-------------------------------------------
                   2782: 
1.45      matthew  2783: =pod
                   2784: 
1.1256    raeburn  2785: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2786: 
                   2787: Returns a string containing a <select name='$name' size='1'> form to 
                   2788: allow a user to select the domain to preform an operation in.  
                   2789: See loncreateuser.pm for an example invocation and use.
                   2790: 
1.90      www      2791: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2792: selected");
                   2793: 
1.743     raeburn  2794: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2795: 
1.910     raeburn  2796: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2797: 
1.1121    raeburn  2798: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2799: 
                   2800: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2801: 
1.1256    raeburn  2802: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2803: 
1.35      matthew  2804: =cut
                   2805: 
                   2806: #-------------------------------------------
1.34      matthew  2807: sub select_dom_form {
1.1256    raeburn  2808:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2809:     if ($onchange) {
1.874     raeburn  2810:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2811:     }
1.1256    raeburn  2812:     if ($disabled) {
                   2813:         $disabled = ' disabled="disabled"';
                   2814:     }
1.1121    raeburn  2815:     my (@domains,%exclude);
1.910     raeburn  2816:     if (ref($incdoms) eq 'ARRAY') {
                   2817:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2818:     } else {
                   2819:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2820:     }
1.90      www      2821:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2822:     if (ref($excdoms) eq 'ARRAY') {
                   2823:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2824:     }
1.1256    raeburn  2825:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2826:     foreach my $dom (@domains) {
1.1121    raeburn  2827:         next if ($exclude{$dom});
1.356     albertel 2828:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2829:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2830:         if ($showdomdesc) {
                   2831:             if ($dom ne '') {
                   2832:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2833:                 if ($domdesc ne '') {
                   2834:                     $selectdomain .= ' ('.$domdesc.')';
                   2835:                 }
                   2836:             } 
                   2837:         }
                   2838:         $selectdomain .= "</option>\n";
1.34      matthew  2839:     }
                   2840:     $selectdomain.="</select>";
                   2841:     return $selectdomain;
                   2842: }
                   2843: 
1.35      matthew  2844: #-------------------------------------------
                   2845: 
1.45      matthew  2846: =pod
                   2847: 
1.648     raeburn  2848: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2849: 
1.586     raeburn  2850: input: 4 arguments (two required, two optional) - 
                   2851:     $domain - domain of new user
                   2852:     $name - name of form element
                   2853:     $default - Value of 'default' causes a default item to be first 
                   2854:                             option, and selected by default. 
                   2855:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2856:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2857: output: returns 2 items: 
1.586     raeburn  2858: (a) form element which contains either:
                   2859:    (i) <select name="$name">
                   2860:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2861:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2862:        </select>
                   2863:        form item if there are multiple library servers in $domain, or
                   2864:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2865:        if there is only one library server in $domain.
                   2866: 
                   2867: (b) number of library servers found.
                   2868: 
                   2869: See loncreateuser.pm for example of use.
1.35      matthew  2870: 
                   2871: =cut
                   2872: 
                   2873: #-------------------------------------------
1.586     raeburn  2874: sub home_server_form_item {
                   2875:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2876:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2877:     my $result;
                   2878:     my $numlib = keys(%servers);
                   2879:     if ($numlib > 1) {
                   2880:         $result .= '<select name="'.$name.'" />'."\n";
                   2881:         if ($default) {
1.804     bisitz   2882:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2883:                        '</option>'."\n";
                   2884:         }
                   2885:         foreach my $hostid (sort(keys(%servers))) {
                   2886:             $result.= '<option value="'.$hostid.'">'.
                   2887: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2888:         }
                   2889:         $result .= '</select>'."\n";
                   2890:     } elsif ($numlib == 1) {
                   2891:         my $hostid;
                   2892:         foreach my $item (keys(%servers)) {
                   2893:             $hostid = $item;
                   2894:         }
                   2895:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2896:                    $hostid.'" />';
                   2897:                    if (!$hide) {
                   2898:                        $result .= $hostid.' '.$servers{$hostid};
                   2899:                    }
                   2900:                    $result .= "\n";
                   2901:     } elsif ($default) {
                   2902:         $result .= '<input type="hidden" name="'.$name.
                   2903:                    '" value="default" />';
                   2904:                    if (!$hide) {
                   2905:                        $result .= &mt('default');
                   2906:                    }
                   2907:                    $result .= "\n";
1.33      matthew  2908:     }
1.586     raeburn  2909:     return ($result,$numlib);
1.33      matthew  2910: }
1.112     bowersj2 2911: 
                   2912: =pod
                   2913: 
1.534     albertel 2914: =back 
                   2915: 
1.112     bowersj2 2916: =cut
1.87      matthew  2917: 
                   2918: ###############################################################
1.112     bowersj2 2919: ##                  Decoding User Agent                      ##
1.87      matthew  2920: ###############################################################
                   2921: 
                   2922: =pod
                   2923: 
1.112     bowersj2 2924: =head1 Decoding the User Agent
                   2925: 
                   2926: =over 4
                   2927: 
                   2928: =item * &decode_user_agent()
1.87      matthew  2929: 
                   2930: Inputs: $r
                   2931: 
                   2932: Outputs:
                   2933: 
                   2934: =over 4
                   2935: 
1.112     bowersj2 2936: =item * $httpbrowser
1.87      matthew  2937: 
1.112     bowersj2 2938: =item * $clientbrowser
1.87      matthew  2939: 
1.112     bowersj2 2940: =item * $clientversion
1.87      matthew  2941: 
1.112     bowersj2 2942: =item * $clientmathml
1.87      matthew  2943: 
1.112     bowersj2 2944: =item * $clientunicode
1.87      matthew  2945: 
1.112     bowersj2 2946: =item * $clientos
1.87      matthew  2947: 
1.1137    raeburn  2948: =item * $clientmobile
                   2949: 
1.1141    raeburn  2950: =item * $clientinfo
                   2951: 
1.1194    raeburn  2952: =item * $clientosversion
                   2953: 
1.87      matthew  2954: =back
                   2955: 
1.157     matthew  2956: =back 
                   2957: 
1.87      matthew  2958: =cut
                   2959: 
                   2960: ###############################################################
                   2961: ###############################################################
                   2962: sub decode_user_agent {
1.247     albertel 2963:     my ($r)=@_;
1.87      matthew  2964:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2965:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2966:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2967:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2968:     my $clientbrowser='unknown';
                   2969:     my $clientversion='0';
                   2970:     my $clientmathml='';
                   2971:     my $clientunicode='0';
1.1137    raeburn  2972:     my $clientmobile=0;
1.1194    raeburn  2973:     my $clientosversion='';
1.87      matthew  2974:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2975:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2976: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2977: 	    $clientbrowser=$bname;
                   2978:             $httpbrowser=~/$vreg/i;
                   2979: 	    $clientversion=$1;
                   2980:             $clientmathml=($clientversion>=$minv);
                   2981:             $clientunicode=($clientversion>=$univ);
                   2982: 	}
                   2983:     }
                   2984:     my $clientos='unknown';
1.1141    raeburn  2985:     my $clientinfo;
1.87      matthew  2986:     if (($httpbrowser=~/linux/i) ||
                   2987:         ($httpbrowser=~/unix/i) ||
                   2988:         ($httpbrowser=~/ux/i) ||
                   2989:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2990:     if (($httpbrowser=~/vax/i) ||
                   2991:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2992:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2993:     if (($httpbrowser=~/mac/i) ||
                   2994:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2995:     if ($httpbrowser=~/win/i) {
                   2996:         $clientos='win';
                   2997:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2998:             $clientosversion = $1;
                   2999:         }
                   3000:     }
1.87      matthew  3001:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3002:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3003:         $clientmobile=lc($1);
                   3004:     }
1.1141    raeburn  3005:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3006:         $clientinfo = 'firefox-'.$1;
                   3007:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3008:         $clientinfo = 'chromeframe-'.$1;
                   3009:     }
1.87      matthew  3010:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3011:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3012:             $clientosversion);
1.87      matthew  3013: }
                   3014: 
1.32      matthew  3015: ###############################################################
                   3016: ##    Authentication changing form generation subroutines    ##
                   3017: ###############################################################
                   3018: ##
                   3019: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3020: ## hash, and have reasonable default values.
                   3021: ##
                   3022: ##    formname = the name given in the <form> tag.
1.35      matthew  3023: #-------------------------------------------
                   3024: 
1.45      matthew  3025: =pod
                   3026: 
1.112     bowersj2 3027: =head1 Authentication Routines
                   3028: 
                   3029: =over 4
                   3030: 
1.648     raeburn  3031: =item * &authform_xxxxxx()
1.35      matthew  3032: 
                   3033: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3034: handle some of the conveniences required for authentication forms.  
                   3035: This is not an optimal method, but it works.  
                   3036: 
                   3037: =over 4
                   3038: 
1.112     bowersj2 3039: =item * authform_header
1.35      matthew  3040: 
1.112     bowersj2 3041: =item * authform_authorwarning
1.35      matthew  3042: 
1.112     bowersj2 3043: =item * authform_nochange
1.35      matthew  3044: 
1.112     bowersj2 3045: =item * authform_kerberos
1.35      matthew  3046: 
1.112     bowersj2 3047: =item * authform_internal
1.35      matthew  3048: 
1.112     bowersj2 3049: =item * authform_filesystem
1.35      matthew  3050: 
1.1310    raeburn  3051: =item * authform_lti
                   3052: 
1.35      matthew  3053: =back
                   3054: 
1.648     raeburn  3055: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3056: 
1.35      matthew  3057: =cut
                   3058: 
                   3059: #-------------------------------------------
1.32      matthew  3060: sub authform_header{  
                   3061:     my %in = (
                   3062:         formname => 'cu',
1.80      albertel 3063:         kerb_def_dom => '',
1.32      matthew  3064:         @_,
                   3065:     );
                   3066:     $in{'formname'} = 'document.' . $in{'formname'};
                   3067:     my $result='';
1.80      albertel 3068: 
                   3069: #---------------------------------------------- Code for upper case translation
                   3070:     my $Javascript_toUpperCase;
                   3071:     unless ($in{kerb_def_dom}) {
                   3072:         $Javascript_toUpperCase =<<"END";
                   3073:         switch (choice) {
                   3074:            case 'krb': currentform.elements[choicearg].value =
                   3075:                currentform.elements[choicearg].value.toUpperCase();
                   3076:                break;
                   3077:            default:
                   3078:         }
                   3079: END
                   3080:     } else {
                   3081:         $Javascript_toUpperCase = "";
                   3082:     }
                   3083: 
1.165     raeburn  3084:     my $radioval = "'nochange'";
1.591     raeburn  3085:     if (defined($in{'curr_authtype'})) {
                   3086:         if ($in{'curr_authtype'} ne '') {
                   3087:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3088:         }
1.174     matthew  3089:     }
1.165     raeburn  3090:     my $argfield = 'null';
1.591     raeburn  3091:     if (defined($in{'mode'})) {
1.165     raeburn  3092:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3093:             if (defined($in{'curr_autharg'})) {
                   3094:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3095:                     $argfield = "'$in{'curr_autharg'}'";
                   3096:                 }
                   3097:             }
                   3098:         }
                   3099:     }
                   3100: 
1.32      matthew  3101:     $result.=<<"END";
                   3102: var current = new Object();
1.165     raeburn  3103: current.radiovalue = $radioval;
                   3104: current.argfield = $argfield;
1.32      matthew  3105: 
                   3106: function changed_radio(choice,currentform) {
                   3107:     var choicearg = choice + 'arg';
                   3108:     // If a radio button in changed, we need to change the argfield
                   3109:     if (current.radiovalue != choice) {
                   3110:         current.radiovalue = choice;
                   3111:         if (current.argfield != null) {
                   3112:             currentform.elements[current.argfield].value = '';
                   3113:         }
                   3114:         if (choice == 'nochange') {
                   3115:             current.argfield = null;
                   3116:         } else {
                   3117:             current.argfield = choicearg;
                   3118:             switch(choice) {
                   3119:                 case 'krb': 
                   3120:                     currentform.elements[current.argfield].value = 
                   3121:                         "$in{'kerb_def_dom'}";
                   3122:                 break;
                   3123:               default:
                   3124:                 break;
                   3125:             }
                   3126:         }
                   3127:     }
                   3128:     return;
                   3129: }
1.22      www      3130: 
1.32      matthew  3131: function changed_text(choice,currentform) {
                   3132:     var choicearg = choice + 'arg';
                   3133:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3134:         $Javascript_toUpperCase
1.32      matthew  3135:         // clear old field
                   3136:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3137:             currentform.elements[current.argfield].value = '';
                   3138:         }
                   3139:         current.argfield = choicearg;
                   3140:     }
                   3141:     set_auth_radio_buttons(choice,currentform);
                   3142:     return;
1.20      www      3143: }
1.32      matthew  3144: 
                   3145: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3146:     var numauthchoices = currentform.login.length;
                   3147:     if (typeof numauthchoices  == "undefined") {
                   3148:         return;
                   3149:     } 
1.32      matthew  3150:     var i=0;
1.986     raeburn  3151:     while (i < numauthchoices) {
1.32      matthew  3152:         if (currentform.login[i].value == newvalue) { break; }
                   3153:         i++;
                   3154:     }
1.986     raeburn  3155:     if (i == numauthchoices) {
1.32      matthew  3156:         return;
                   3157:     }
                   3158:     current.radiovalue = newvalue;
                   3159:     currentform.login[i].checked = true;
                   3160:     return;
                   3161: }
                   3162: END
                   3163:     return $result;
                   3164: }
                   3165: 
1.1106    raeburn  3166: sub authform_authorwarning {
1.32      matthew  3167:     my $result='';
1.144     matthew  3168:     $result='<i>'.
                   3169:         &mt('As a general rule, only authors or co-authors should be '.
                   3170:             'filesystem authenticated '.
                   3171:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3172:     return $result;
                   3173: }
                   3174: 
1.1106    raeburn  3175: sub authform_nochange {
1.32      matthew  3176:     my %in = (
                   3177:               formname => 'document.cu',
                   3178:               kerb_def_dom => 'MSU.EDU',
                   3179:               @_,
                   3180:           );
1.1106    raeburn  3181:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3182:     my $result;
1.1104    raeburn  3183:     if (!$authnum) {
1.1105    raeburn  3184:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3185:     } else {
                   3186:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3187:                   '<input type="radio" name="login" value="nochange" '.
                   3188:                   'checked="checked" onclick="'.
1.281     albertel 3189:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3190: 	    '</label>';
1.586     raeburn  3191:     }
1.32      matthew  3192:     return $result;
                   3193: }
                   3194: 
1.591     raeburn  3195: sub authform_kerberos {
1.32      matthew  3196:     my %in = (
                   3197:               formname => 'document.cu',
                   3198:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3199:               kerb_def_auth => 'krb4',
1.32      matthew  3200:               @_,
                   3201:               );
1.586     raeburn  3202:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3203:         $autharg,$jscall,$disabled);
1.1106    raeburn  3204:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3205:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3206:        $check5 = ' checked="checked"';
1.80      albertel 3207:     } else {
1.772     bisitz   3208:        $check4 = ' checked="checked"';
1.80      albertel 3209:     }
1.1259    raeburn  3210:     if ($in{'readonly'}) {
                   3211:         $disabled = ' disabled="disabled"';
                   3212:     }
1.165     raeburn  3213:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3214:     if (defined($in{'curr_authtype'})) {
                   3215:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3216:             $krbcheck = ' checked="checked"';
1.623     raeburn  3217:             if (defined($in{'mode'})) {
                   3218:                 if ($in{'mode'} eq 'modifyuser') {
                   3219:                     $krbcheck = '';
                   3220:                 }
                   3221:             }
1.591     raeburn  3222:             if (defined($in{'curr_kerb_ver'})) {
                   3223:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3224:                     $check5 = ' checked="checked"';
1.591     raeburn  3225:                     $check4 = '';
                   3226:                 } else {
1.772     bisitz   3227:                     $check4 = ' checked="checked"';
1.591     raeburn  3228:                     $check5 = '';
                   3229:                 }
1.586     raeburn  3230:             }
1.591     raeburn  3231:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3232:                 $krbarg = $in{'curr_autharg'};
                   3233:             }
1.586     raeburn  3234:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3235:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3236:                     $result = 
                   3237:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3238:         $in{'curr_autharg'},$krbver);
                   3239:                 } else {
                   3240:                     $result =
                   3241:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3242:                 }
                   3243:                 return $result; 
                   3244:             }
                   3245:         }
                   3246:     } else {
                   3247:         if ($authnum == 1) {
1.784     bisitz   3248:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3249:         }
                   3250:     }
1.586     raeburn  3251:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3252:         return;
1.587     raeburn  3253:     } elsif ($authtype eq '') {
1.591     raeburn  3254:         if (defined($in{'mode'})) {
1.587     raeburn  3255:             if ($in{'mode'} eq 'modifycourse') {
                   3256:                 if ($authnum == 1) {
1.1259    raeburn  3257:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3258:                 }
                   3259:             }
                   3260:         }
1.586     raeburn  3261:     }
                   3262:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3263:     if ($authtype eq '') {
                   3264:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3265:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3266:                     $krbcheck.$disabled.' />';
1.586     raeburn  3267:     }
                   3268:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3269:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3270:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3271:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3272:          $in{'curr_authtype'} eq 'krb4')) {
                   3273:         $result .= &mt
1.144     matthew  3274:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3275:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3276:          '<label>'.$authtype,
1.281     albertel 3277:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3278:              'value="'.$krbarg.'" '.
1.1259    raeburn  3279:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3280:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3281:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3282: 	 '</label>');
1.586     raeburn  3283:     } elsif ($can_assign{'krb4'}) {
                   3284:         $result .= &mt
                   3285:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3286:          '[_3] Version 4 [_4]',
                   3287:          '<label>'.$authtype,
                   3288:          '</label><input type="text" size="10" name="krbarg" '.
                   3289:              'value="'.$krbarg.'" '.
1.1259    raeburn  3290:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3291:          '<label><input type="hidden" name="krbver" value="4" />',
                   3292:          '</label>');
                   3293:     } elsif ($can_assign{'krb5'}) {
                   3294:         $result .= &mt
                   3295:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3296:          '[_3] Version 5 [_4]',
                   3297:          '<label>'.$authtype,
                   3298:          '</label><input type="text" size="10" name="krbarg" '.
                   3299:              'value="'.$krbarg.'" '.
1.1259    raeburn  3300:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3301:          '<label><input type="hidden" name="krbver" value="5" />',
                   3302:          '</label>');
                   3303:     }
1.32      matthew  3304:     return $result;
                   3305: }
                   3306: 
1.1106    raeburn  3307: sub authform_internal {
1.586     raeburn  3308:     my %in = (
1.32      matthew  3309:                 formname => 'document.cu',
                   3310:                 kerb_def_dom => 'MSU.EDU',
                   3311:                 @_,
                   3312:                 );
1.1259    raeburn  3313:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3314:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3315:     if ($in{'readonly'}) {
                   3316:         $disabled = ' disabled="disabled"';
                   3317:     }
1.591     raeburn  3318:     if (defined($in{'curr_authtype'})) {
                   3319:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3320:             if ($can_assign{'int'}) {
1.772     bisitz   3321:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3322:                 if (defined($in{'mode'})) {
                   3323:                     if ($in{'mode'} eq 'modifyuser') {
                   3324:                         $intcheck = '';
                   3325:                     }
                   3326:                 }
1.591     raeburn  3327:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3328:                     $intarg = $in{'curr_autharg'};
                   3329:                 }
                   3330:             } else {
                   3331:                 $result = &mt('Currently internally authenticated.');
                   3332:                 return $result;
1.165     raeburn  3333:             }
                   3334:         }
1.586     raeburn  3335:     } else {
                   3336:         if ($authnum == 1) {
1.784     bisitz   3337:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3338:         }
                   3339:     }
                   3340:     if (!$can_assign{'int'}) {
                   3341:         return;
1.587     raeburn  3342:     } elsif ($authtype eq '') {
1.591     raeburn  3343:         if (defined($in{'mode'})) {
1.587     raeburn  3344:             if ($in{'mode'} eq 'modifycourse') {
                   3345:                 if ($authnum == 1) {
1.1259    raeburn  3346:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3347:                 }
                   3348:             }
                   3349:         }
1.165     raeburn  3350:     }
1.586     raeburn  3351:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3352:     if ($authtype eq '') {
                   3353:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3354:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3355:     }
1.605     bisitz   3356:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3357:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3358:     $result = &mt
1.144     matthew  3359:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3360:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3361:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3362:     return $result;
                   3363: }
                   3364: 
1.1104    raeburn  3365: sub authform_local {
1.32      matthew  3366:     my %in = (
                   3367:               formname => 'document.cu',
                   3368:               kerb_def_dom => 'MSU.EDU',
                   3369:               @_,
                   3370:               );
1.1259    raeburn  3371:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3372:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3373:     if ($in{'readonly'}) {
                   3374:         $disabled = ' disabled="disabled"';
                   3375:     } 
1.591     raeburn  3376:     if (defined($in{'curr_authtype'})) {
                   3377:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3378:             if ($can_assign{'loc'}) {
1.772     bisitz   3379:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3380:                 if (defined($in{'mode'})) {
                   3381:                     if ($in{'mode'} eq 'modifyuser') {
                   3382:                         $loccheck = '';
                   3383:                     }
                   3384:                 }
1.591     raeburn  3385:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3386:                     $locarg = $in{'curr_autharg'};
                   3387:                 }
                   3388:             } else {
                   3389:                 $result = &mt('Currently using local (institutional) authentication.');
                   3390:                 return $result;
1.165     raeburn  3391:             }
                   3392:         }
1.586     raeburn  3393:     } else {
                   3394:         if ($authnum == 1) {
1.784     bisitz   3395:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3396:         }
                   3397:     }
                   3398:     if (!$can_assign{'loc'}) {
                   3399:         return;
1.587     raeburn  3400:     } elsif ($authtype eq '') {
1.591     raeburn  3401:         if (defined($in{'mode'})) {
1.587     raeburn  3402:             if ($in{'mode'} eq 'modifycourse') {
                   3403:                 if ($authnum == 1) {
1.1259    raeburn  3404:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3405:                 }
                   3406:             }
                   3407:         }
1.165     raeburn  3408:     }
1.586     raeburn  3409:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3410:     if ($authtype eq '') {
                   3411:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3412:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3413:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3414:     }
                   3415:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3416:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3417:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3418:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3419:     return $result;
                   3420: }
                   3421: 
1.1106    raeburn  3422: sub authform_filesystem {
1.32      matthew  3423:     my %in = (
                   3424:               formname => 'document.cu',
                   3425:               kerb_def_dom => 'MSU.EDU',
                   3426:               @_,
                   3427:               );
1.1259    raeburn  3428:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3429:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3430:     if ($in{'readonly'}) {
                   3431:         $disabled = ' disabled="disabled"';
                   3432:     }
1.591     raeburn  3433:     if (defined($in{'curr_authtype'})) {
                   3434:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3435:             if ($can_assign{'fsys'}) {
1.772     bisitz   3436:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3437:                 if (defined($in{'mode'})) {
                   3438:                     if ($in{'mode'} eq 'modifyuser') {
                   3439:                         $fsyscheck = '';
                   3440:                     }
                   3441:                 }
1.586     raeburn  3442:             } else {
                   3443:                 $result = &mt('Currently Filesystem Authenticated.');
                   3444:                 return $result;
1.1259    raeburn  3445:             }
1.586     raeburn  3446:         }
                   3447:     } else {
                   3448:         if ($authnum == 1) {
1.784     bisitz   3449:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3450:         }
                   3451:     }
                   3452:     if (!$can_assign{'fsys'}) {
                   3453:         return;
1.587     raeburn  3454:     } elsif ($authtype eq '') {
1.591     raeburn  3455:         if (defined($in{'mode'})) {
1.587     raeburn  3456:             if ($in{'mode'} eq 'modifycourse') {
                   3457:                 if ($authnum == 1) {
1.1259    raeburn  3458:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3459:                 }
                   3460:             }
                   3461:         }
1.586     raeburn  3462:     }
                   3463:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3464:     if ($authtype eq '') {
                   3465:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3466:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3467:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3468:     }
1.1310    raeburn  3469:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3470:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3471:     $result = &mt
1.144     matthew  3472:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3473:          '<label>'.$authtype,'</label>'.$autharg);
                   3474:     return $result;
                   3475: }
                   3476: 
                   3477: sub authform_lti {
                   3478:     my %in = (
                   3479:               formname => 'document.cu',
                   3480:               kerb_def_dom => 'MSU.EDU',
                   3481:               @_,
                   3482:               );
                   3483:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3484:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3485:     if ($in{'readonly'}) {
                   3486:         $disabled = ' disabled="disabled"';
                   3487:     }
                   3488:     if (defined($in{'curr_authtype'})) {
                   3489:         if ($in{'curr_authtype'} eq 'lti') {
                   3490:             if ($can_assign{'lti'}) {
                   3491:                 $lticheck = 'checked="checked" ';
                   3492:                 if (defined($in{'mode'})) {
                   3493:                     if ($in{'mode'} eq 'modifyuser') {
                   3494:                         $lticheck = '';
                   3495:                     }
                   3496:                 }
                   3497:             } else {
                   3498:                 $result = &mt('Currently LTI Authenticated.');
                   3499:                 return $result;
                   3500:             }
                   3501:         }
                   3502:     } else {
                   3503:         if ($authnum == 1) {
                   3504:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3505:         }
                   3506:     }
                   3507:     if (!$can_assign{'lti'}) {
                   3508:         return;
                   3509:     } elsif ($authtype eq '') {
                   3510:         if (defined($in{'mode'})) {
                   3511:             if ($in{'mode'} eq 'modifycourse') {
                   3512:                 if ($authnum == 1) {
                   3513:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3514:                 }
                   3515:             }
                   3516:         }
                   3517:     }
                   3518:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3519:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3520:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3521:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3522:                     $jscall.'"'.$disabled.' />';
                   3523:     }
                   3524:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3525:     if ($authtype) {
                   3526:         $result = &mt('[_1] LTI Authenticated',
                   3527:                       '<label>'.$authtype.'</label>'.$autharg);
                   3528:     } else {
                   3529:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3530:                   $autharg;
                   3531:     }
1.32      matthew  3532:     return $result;
                   3533: }
                   3534: 
1.586     raeburn  3535: sub get_assignable_auth {
                   3536:     my ($dom) = @_;
                   3537:     if ($dom eq '') {
                   3538:         $dom = $env{'request.role.domain'};
                   3539:     }
                   3540:     my %can_assign = (
                   3541:                           krb4 => 1,
                   3542:                           krb5 => 1,
                   3543:                           int  => 1,
                   3544:                           loc  => 1,
1.1310    raeburn  3545:                           lti  => 1,
1.586     raeburn  3546:                      );
                   3547:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3548:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3549:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3550:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3551:             my $context;
                   3552:             if ($env{'request.role'} =~ /^au/) {
                   3553:                 $context = 'author';
1.1259    raeburn  3554:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3555:                 $context = 'domain';
                   3556:             } elsif ($env{'request.course.id'}) {
                   3557:                 $context = 'course';
                   3558:             }
                   3559:             if ($context) {
                   3560:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3561:                    %can_assign = %{$authhash->{$context}}; 
                   3562:                 }
                   3563:             }
                   3564:         }
                   3565:     }
                   3566:     my $authnum = 0;
                   3567:     foreach my $key (keys(%can_assign)) {
                   3568:         if ($can_assign{$key}) {
                   3569:             $authnum ++;
                   3570:         }
                   3571:     }
                   3572:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3573:         $authnum --;
                   3574:     }
                   3575:     return ($authnum,%can_assign);
                   3576: }
                   3577: 
1.1331    raeburn  3578: sub check_passwd_rules {
                   3579:     my ($domain,$plainpass) = @_;
                   3580:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3581:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3582:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3583:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3584:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3585:             if ($passwdconf{'min'} > $min) {
                   3586:                 $min = $passwdconf{'min'};
                   3587:             }
1.1331    raeburn  3588:         }
                   3589:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3590:             $max = $passwdconf{'max'};
                   3591:         }
                   3592:         @chars = @{$passwdconf{'chars'}};
                   3593:     }
                   3594:     if (($min) && (length($plainpass) < $min)) {
                   3595:         push(@brokerule,'min');
                   3596:     }
                   3597:     if (($max) && (length($plainpass) > $max)) {
                   3598:         push(@brokerule,'max');
                   3599:     }
                   3600:     if (@chars) {
                   3601:         my %rules;
                   3602:         map { $rules{$_} = 1; } @chars;
                   3603:         if ($rules{'uc'}) {
                   3604:             unless ($plainpass =~ /[A-Z]/) {
                   3605:                 push(@brokerule,'uc');
                   3606:             }
                   3607:         }
                   3608:         if ($rules{'lc'}) {
1.1332    raeburn  3609:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3610:                 push(@brokerule,'lc');
                   3611:             }
                   3612:         }
                   3613:         if ($rules{'num'}) {
                   3614:             unless ($plainpass =~ /\d/) {
                   3615:                 push(@brokerule,'num');
                   3616:             }
                   3617:         }
                   3618:         if ($rules{'spec'}) {
                   3619:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3620:                 push(@brokerule,'spec');
                   3621:             }
                   3622:         }
                   3623:     }
                   3624:     if (@brokerule) {
                   3625:         my %rulenames = &Apache::lonlocal::texthash(
                   3626:             uc   => 'At least one upper case letter',
                   3627:             lc   => 'At least one lower case letter',
                   3628:             num  => 'At least one number',
                   3629:             spec => 'At least one non-alphanumeric',
                   3630:         );
                   3631:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3632:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3633:         $rulenames{'num'} .= ': 0123456789';
                   3634:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3635:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3636:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3637:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3638:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3639:             if (grep(/^$rule$/,@brokerule)) {
                   3640:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3641:             }
                   3642:         }
                   3643:         $warning .= '</ul>';
                   3644:     }
1.1332    raeburn  3645:     if (wantarray) {
                   3646:         return @brokerule;
                   3647:     }
1.1331    raeburn  3648:     return $warning;
                   3649: }
                   3650: 
1.80      albertel 3651: ###############################################################
                   3652: ##    Get Kerberos Defaults for Domain                 ##
                   3653: ###############################################################
                   3654: ##
                   3655: ## Returns default kerberos version and an associated argument
                   3656: ## as listed in file domain.tab. If not listed, provides
                   3657: ## appropriate default domain and kerberos version.
                   3658: ##
                   3659: #-------------------------------------------
                   3660: 
                   3661: =pod
                   3662: 
1.648     raeburn  3663: =item * &get_kerberos_defaults()
1.80      albertel 3664: 
                   3665: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3666: version and domain. If not found, it defaults to version 4 and the 
                   3667: domain of the server.
1.80      albertel 3668: 
1.648     raeburn  3669: =over 4
                   3670: 
1.80      albertel 3671: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3672: 
1.648     raeburn  3673: =back
                   3674: 
                   3675: =back
                   3676: 
1.80      albertel 3677: =cut
                   3678: 
                   3679: #-------------------------------------------
                   3680: sub get_kerberos_defaults {
                   3681:     my $domain=shift;
1.641     raeburn  3682:     my ($krbdef,$krbdefdom);
                   3683:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3684:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3685:         $krbdef = $domdefaults{'auth_def'};
                   3686:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3687:     } else {
1.80      albertel 3688:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3689:         my $krbdefdom=$1;
                   3690:         $krbdefdom=~tr/a-z/A-Z/;
                   3691:         $krbdef = "krb4";
                   3692:     }
                   3693:     return ($krbdef,$krbdefdom);
                   3694: }
1.112     bowersj2 3695: 
1.32      matthew  3696: 
1.46      matthew  3697: ###############################################################
                   3698: ##                Thesaurus Functions                        ##
                   3699: ###############################################################
1.20      www      3700: 
1.46      matthew  3701: =pod
1.20      www      3702: 
1.112     bowersj2 3703: =head1 Thesaurus Functions
                   3704: 
                   3705: =over 4
                   3706: 
1.648     raeburn  3707: =item * &initialize_keywords()
1.46      matthew  3708: 
                   3709: Initializes the package variable %Keywords if it is empty.  Uses the
                   3710: package variable $thesaurus_db_file.
                   3711: 
                   3712: =cut
                   3713: 
                   3714: ###################################################
                   3715: 
                   3716: sub initialize_keywords {
                   3717:     return 1 if (scalar keys(%Keywords));
                   3718:     # If we are here, %Keywords is empty, so fill it up
                   3719:     #   Make sure the file we need exists...
                   3720:     if (! -e $thesaurus_db_file) {
                   3721:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3722:                                  " failed because it does not exist");
                   3723:         return 0;
                   3724:     }
                   3725:     #   Set up the hash as a database
                   3726:     my %thesaurus_db;
                   3727:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3728:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3729:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3730:                                  $thesaurus_db_file);
                   3731:         return 0;
                   3732:     } 
                   3733:     #  Get the average number of appearances of a word.
                   3734:     my $avecount = $thesaurus_db{'average.count'};
                   3735:     #  Put keywords (those that appear > average) into %Keywords
                   3736:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3737:         my ($count,undef) = split /:/,$data;
                   3738:         $Keywords{$word}++ if ($count > $avecount);
                   3739:     }
                   3740:     untie %thesaurus_db;
                   3741:     # Remove special values from %Keywords.
1.356     albertel 3742:     foreach my $value ('total.count','average.count') {
                   3743:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3744:   }
1.46      matthew  3745:     return 1;
                   3746: }
                   3747: 
                   3748: ###################################################
                   3749: 
                   3750: =pod
                   3751: 
1.648     raeburn  3752: =item * &keyword($word)
1.46      matthew  3753: 
                   3754: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3755: than the average number of times in the thesaurus database.  Calls 
                   3756: &initialize_keywords
                   3757: 
                   3758: =cut
                   3759: 
                   3760: ###################################################
1.20      www      3761: 
                   3762: sub keyword {
1.46      matthew  3763:     return if (!&initialize_keywords());
                   3764:     my $word=lc(shift());
                   3765:     $word=~s/\W//g;
                   3766:     return exists($Keywords{$word});
1.20      www      3767: }
1.46      matthew  3768: 
                   3769: ###############################################################
                   3770: 
                   3771: =pod 
1.20      www      3772: 
1.648     raeburn  3773: =item * &get_related_words()
1.46      matthew  3774: 
1.160     matthew  3775: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3776: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3777: will be returned.  The order of the words returned is determined by the
                   3778: database which holds them.
                   3779: 
                   3780: Uses global $thesaurus_db_file.
                   3781: 
1.1057    foxr     3782: 
1.46      matthew  3783: =cut
                   3784: 
                   3785: ###############################################################
                   3786: sub get_related_words {
                   3787:     my $keyword = shift;
                   3788:     my %thesaurus_db;
                   3789:     if (! -e $thesaurus_db_file) {
                   3790:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3791:                                  "failed because the file does not exist");
                   3792:         return ();
                   3793:     }
                   3794:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3795:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3796:         return ();
                   3797:     } 
                   3798:     my @Words=();
1.429     www      3799:     my $count=0;
1.46      matthew  3800:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3801: 	# The first element is the number of times
                   3802: 	# the word appears.  We do not need it now.
1.429     www      3803: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3804: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3805: 	my $threshold=$mostfrequentcount/10;
                   3806:         foreach my $possibleword (@RelatedWords) {
                   3807:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3808:             if ($wordcount>$threshold) {
                   3809: 		push(@Words,$word);
                   3810:                 $count++;
                   3811:                 if ($count>10) { last; }
                   3812: 	    }
1.20      www      3813:         }
                   3814:     }
1.46      matthew  3815:     untie %thesaurus_db;
                   3816:     return @Words;
1.14      harris41 3817: }
1.1090    foxr     3818: ###############################################################
                   3819: #
                   3820: #  Spell checking
                   3821: #
                   3822: 
                   3823: =pod
                   3824: 
1.1142    raeburn  3825: =back
                   3826: 
1.1090    foxr     3827: =head1 Spell checking
                   3828: 
                   3829: =over 4
                   3830: 
                   3831: =item * &check_spelling($wordlist $language)
                   3832: 
                   3833: Takes a string containing words and feeds it to an external
                   3834: spellcheck program via a pipeline. Returns a string containing
                   3835: them mis-spelled words.
                   3836: 
                   3837: Parameters:
                   3838: 
                   3839: =over 4
                   3840: 
                   3841: =item - $wordlist
                   3842: 
                   3843: String that will be fed into the spellcheck program.
                   3844: 
                   3845: =item - $language
                   3846: 
                   3847: Language string that specifies the language for which the spell
                   3848: check will be performed.
                   3849: 
                   3850: =back
                   3851: 
                   3852: =back
                   3853: 
                   3854: Note: This sub assumes that aspell is installed.
                   3855: 
                   3856: 
                   3857: =cut
                   3858: 
1.46      matthew  3859: 
1.1090    foxr     3860: sub check_spelling {
                   3861:     my ($wordlist, $language) = @_;
1.1091    foxr     3862:     my @misspellings;
                   3863:     
                   3864:     # Generate the speller and set the langauge.
                   3865:     # if explicitly selected:
1.1090    foxr     3866: 
1.1091    foxr     3867:     my $speller = Text::Aspell->new;
1.1090    foxr     3868:     if ($language) {
1.1091    foxr     3869: 	$speller->set_option('lang', $language);
1.1090    foxr     3870:     }
                   3871: 
1.1091    foxr     3872:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3873: 
1.1091    foxr     3874:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3875: 
1.1091    foxr     3876:     foreach my $word (@words) {
                   3877: 	if(! $speller->check($word)) {
                   3878: 	    push(@misspellings, $word);
1.1090    foxr     3879: 	}
                   3880:     }
1.1091    foxr     3881:     return join(' ', @misspellings);
                   3882:     
1.1090    foxr     3883: }
                   3884: 
1.61      www      3885: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3886: =pod
                   3887: 
1.112     bowersj2 3888: =head1 User Name Functions
                   3889: 
                   3890: =over 4
                   3891: 
1.648     raeburn  3892: =item * &plainname($uname,$udom,$first)
1.81      albertel 3893: 
1.112     bowersj2 3894: Takes a users logon name and returns it as a string in
1.226     albertel 3895: "first middle last generation" form 
                   3896: if $first is set to 'lastname' then it returns it as
                   3897: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3898: 
                   3899: =cut
1.61      www      3900: 
1.295     www      3901: 
1.81      albertel 3902: ###############################################################
1.61      www      3903: sub plainname {
1.226     albertel 3904:     my ($uname,$udom,$first)=@_;
1.537     albertel 3905:     return if (!defined($uname) || !defined($udom));
1.295     www      3906:     my %names=&getnames($uname,$udom);
1.226     albertel 3907:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3908: 					  $names{'middlename'},
                   3909: 					  $names{'lastname'},
                   3910: 					  $names{'generation'},$first);
                   3911:     $name=~s/^\s+//;
1.62      www      3912:     $name=~s/\s+$//;
                   3913:     $name=~s/\s+/ /g;
1.353     albertel 3914:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3915:     return $name;
1.61      www      3916: }
1.66      www      3917: 
                   3918: # -------------------------------------------------------------------- Nickname
1.81      albertel 3919: =pod
                   3920: 
1.648     raeburn  3921: =item * &nickname($uname,$udom)
1.81      albertel 3922: 
                   3923: Gets a users name and returns it as a string as
                   3924: 
                   3925: "&quot;nickname&quot;"
1.66      www      3926: 
1.81      albertel 3927: if the user has a nickname or
                   3928: 
                   3929: "first middle last generation"
                   3930: 
                   3931: if the user does not
                   3932: 
                   3933: =cut
1.66      www      3934: 
                   3935: sub nickname {
                   3936:     my ($uname,$udom)=@_;
1.537     albertel 3937:     return if (!defined($uname) || !defined($udom));
1.295     www      3938:     my %names=&getnames($uname,$udom);
1.68      albertel 3939:     my $name=$names{'nickname'};
1.66      www      3940:     if ($name) {
                   3941:        $name='&quot;'.$name.'&quot;'; 
                   3942:     } else {
                   3943:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3944: 	     $names{'lastname'}.' '.$names{'generation'};
                   3945:        $name=~s/\s+$//;
                   3946:        $name=~s/\s+/ /g;
                   3947:     }
                   3948:     return $name;
                   3949: }
                   3950: 
1.295     www      3951: sub getnames {
                   3952:     my ($uname,$udom)=@_;
1.537     albertel 3953:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3954:     if ($udom eq 'public' && $uname eq 'public') {
                   3955: 	return ('lastname' => &mt('Public'));
                   3956:     }
1.295     www      3957:     my $id=$uname.':'.$udom;
                   3958:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3959:     if ($cached) {
                   3960: 	return %{$names};
                   3961:     } else {
                   3962: 	my %loadnames=&Apache::lonnet::get('environment',
                   3963:                     ['firstname','middlename','lastname','generation','nickname'],
                   3964: 					 $udom,$uname);
                   3965: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3966: 	return %loadnames;
                   3967:     }
                   3968: }
1.61      www      3969: 
1.542     raeburn  3970: # -------------------------------------------------------------------- getemails
1.648     raeburn  3971: 
1.542     raeburn  3972: =pod
                   3973: 
1.648     raeburn  3974: =item * &getemails($uname,$udom)
1.542     raeburn  3975: 
                   3976: Gets a user's email information and returns it as a hash with keys:
                   3977: notification, critnotification, permanentemail
                   3978: 
                   3979: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3980: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3981:  
1.648     raeburn  3982: 
1.542     raeburn  3983: =cut
                   3984: 
1.648     raeburn  3985: 
1.466     albertel 3986: sub getemails {
                   3987:     my ($uname,$udom)=@_;
                   3988:     if ($udom eq 'public' && $uname eq 'public') {
                   3989: 	return;
                   3990:     }
1.467     www      3991:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3992:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3993:     my $id=$uname.':'.$udom;
                   3994:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3995:     if ($cached) {
                   3996: 	return %{$names};
                   3997:     } else {
                   3998: 	my %loadnames=&Apache::lonnet::get('environment',
                   3999:                     			   ['notification','critnotification',
                   4000: 					    'permanentemail'],
                   4001: 					   $udom,$uname);
                   4002: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4003: 	return %loadnames;
                   4004:     }
                   4005: }
                   4006: 
1.551     albertel 4007: sub flush_email_cache {
                   4008:     my ($uname,$udom)=@_;
                   4009:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4010:     if (!$uname) { $uname=$env{'user.name'};   }
                   4011:     return if ($udom eq 'public' && $uname eq 'public');
                   4012:     my $id=$uname.':'.$udom;
                   4013:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4014: }
                   4015: 
1.728     raeburn  4016: # -------------------------------------------------------------------- getlangs
                   4017: 
                   4018: =pod
                   4019: 
                   4020: =item * &getlangs($uname,$udom)
                   4021: 
                   4022: Gets a user's language preference and returns it as a hash with key:
                   4023: language.
                   4024: 
                   4025: =cut
                   4026: 
                   4027: 
                   4028: sub getlangs {
                   4029:     my ($uname,$udom) = @_;
                   4030:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4031:     if (!$uname) { $uname=$env{'user.name'};   }
                   4032:     my $id=$uname.':'.$udom;
                   4033:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4034:     if ($cached) {
                   4035:         return %{$langs};
                   4036:     } else {
                   4037:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4038:                                            $udom,$uname);
                   4039:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4040:         return %loadlangs;
                   4041:     }
                   4042: }
                   4043: 
                   4044: sub flush_langs_cache {
                   4045:     my ($uname,$udom)=@_;
                   4046:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4047:     if (!$uname) { $uname=$env{'user.name'};   }
                   4048:     return if ($udom eq 'public' && $uname eq 'public');
                   4049:     my $id=$uname.':'.$udom;
                   4050:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4051: }
                   4052: 
1.61      www      4053: # ------------------------------------------------------------------ Screenname
1.81      albertel 4054: 
                   4055: =pod
                   4056: 
1.648     raeburn  4057: =item * &screenname($uname,$udom)
1.81      albertel 4058: 
                   4059: Gets a users screenname and returns it as a string
                   4060: 
                   4061: =cut
1.61      www      4062: 
                   4063: sub screenname {
                   4064:     my ($uname,$udom)=@_;
1.258     albertel 4065:     if ($uname eq $env{'user.name'} &&
                   4066: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4067:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4068:     return $names{'screenname'};
1.62      www      4069: }
                   4070: 
1.212     albertel 4071: 
1.802     bisitz   4072: # ------------------------------------------------------------- Confirm Wrapper
                   4073: =pod
                   4074: 
1.1142    raeburn  4075: =item * &confirmwrapper($message)
1.802     bisitz   4076: 
                   4077: Wrap messages about completion of operation in box
                   4078: 
                   4079: =cut
                   4080: 
                   4081: sub confirmwrapper {
                   4082:     my ($message)=@_;
                   4083:     if ($message) {
                   4084:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4085:                .$message."\n"
                   4086:                .'</div>'."\n";
                   4087:     } else {
                   4088:         return $message;
                   4089:     }
                   4090: }
                   4091: 
1.62      www      4092: # ------------------------------------------------------------- Message Wrapper
                   4093: 
                   4094: sub messagewrapper {
1.369     www      4095:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4096:     return 
1.441     albertel 4097:         '<a href="/adm/email?compose=individual&amp;'.
                   4098:         'recname='.$username.'&amp;recdom='.$domain.
                   4099: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4100:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4101: }
1.802     bisitz   4102: 
1.74      www      4103: # --------------------------------------------------------------- Notes Wrapper
                   4104: 
                   4105: sub noteswrapper {
                   4106:     my ($link,$un,$do)=@_;
                   4107:     return 
1.896     amueller 4108: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4109: }
1.802     bisitz   4110: 
1.62      www      4111: # ------------------------------------------------------------- Aboutme Wrapper
                   4112: 
                   4113: sub aboutmewrapper {
1.1070    raeburn  4114:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4115:     if (!defined($username)  && !defined($domain)) {
                   4116:         return;
                   4117:     }
1.1096    raeburn  4118:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4119: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4120: }
                   4121: 
                   4122: # ------------------------------------------------------------ Syllabus Wrapper
                   4123: 
                   4124: sub syllabuswrapper {
1.707     bisitz   4125:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4126:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4127: }
1.14      harris41 4128: 
1.802     bisitz   4129: # -----------------------------------------------------------------------------
                   4130: 
1.208     matthew  4131: sub track_student_link {
1.887     raeburn  4132:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4133:     my $link ="/adm/trackstudent?";
1.208     matthew  4134:     my $title = 'View recent activity';
                   4135:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4136:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4137:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4138:         $title .= ' of this student';
1.268     albertel 4139:     } 
1.208     matthew  4140:     if (defined($target) && $target !~ /^\s*$/) {
                   4141:         $target = qq{target="$target"};
                   4142:     } else {
                   4143:         $target = '';
                   4144:     }
1.268     albertel 4145:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4146:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4147:     $title = &mt($title);
                   4148:     $linktext = &mt($linktext);
1.448     albertel 4149:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4150: 	&help_open_topic('View_recent_activity');
1.208     matthew  4151: }
                   4152: 
1.781     raeburn  4153: sub slot_reservations_link {
                   4154:     my ($linktext,$sname,$sdom,$target) = @_;
                   4155:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4156:     my $title = 'View slot reservation history';
                   4157:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4158:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4159:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4160:         $title .= ' of this student';
                   4161:     }
                   4162:     if (defined($target) && $target !~ /^\s*$/) {
                   4163:         $target = qq{target="$target"};
                   4164:     } else {
                   4165:         $target = '';
                   4166:     }
                   4167:     $title = &mt($title);
                   4168:     $linktext = &mt($linktext);
                   4169:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4170: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4171: 
                   4172: }
                   4173: 
1.508     www      4174: # ===================================================== Display a student photo
                   4175: 
                   4176: 
1.509     albertel 4177: sub student_image_tag {
1.508     www      4178:     my ($domain,$user)=@_;
                   4179:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4180:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4181: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4182:     } else {
                   4183: 	return '';
                   4184:     }
                   4185: }
                   4186: 
1.112     bowersj2 4187: =pod
                   4188: 
                   4189: =back
                   4190: 
                   4191: =head1 Access .tab File Data
                   4192: 
                   4193: =over 4
                   4194: 
1.648     raeburn  4195: =item * &languageids() 
1.112     bowersj2 4196: 
                   4197: returns list of all language ids
                   4198: 
                   4199: =cut
                   4200: 
1.14      harris41 4201: sub languageids {
1.16      harris41 4202:     return sort(keys(%language));
1.14      harris41 4203: }
                   4204: 
1.112     bowersj2 4205: =pod
                   4206: 
1.648     raeburn  4207: =item * &languagedescription() 
1.112     bowersj2 4208: 
                   4209: returns description of a specified language id
                   4210: 
                   4211: =cut
                   4212: 
1.14      harris41 4213: sub languagedescription {
1.125     www      4214:     my $code=shift;
                   4215:     return  ($supported_language{$code}?'* ':'').
                   4216:             $language{$code}.
1.126     www      4217: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4218: }
                   4219: 
1.1048    foxr     4220: =pod
                   4221: 
                   4222: =item * &plainlanguagedescription
                   4223: 
                   4224: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4225: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4226: 
                   4227: =cut
                   4228: 
1.145     www      4229: sub plainlanguagedescription {
                   4230:     my $code=shift;
                   4231:     return $language{$code};
                   4232: }
                   4233: 
1.1048    foxr     4234: =pod
                   4235: 
                   4236: =item * &supportedlanguagecode
                   4237: 
                   4238: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4239: code.
                   4240: 
                   4241: =cut
                   4242: 
1.145     www      4243: sub supportedlanguagecode {
                   4244:     my $code=shift;
                   4245:     return $supported_language{$code};
1.97      www      4246: }
                   4247: 
1.112     bowersj2 4248: =pod
                   4249: 
1.1048    foxr     4250: =item * &latexlanguage()
                   4251: 
                   4252: Given a language key code returns the correspondnig language to use
                   4253: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4254: is no supported hyphenation for the language code.
                   4255: 
                   4256: =cut
                   4257: 
                   4258: sub latexlanguage {
                   4259:     my $code = shift;
                   4260:     return $latex_language{$code};
                   4261: }
                   4262: 
                   4263: =pod
                   4264: 
                   4265: =item * &latexhyphenation()
                   4266: 
                   4267: Same as above but what's supplied is the language as it might be stored
                   4268: in the metadata.
                   4269: 
                   4270: =cut
                   4271: 
                   4272: sub latexhyphenation {
                   4273:     my $key = shift;
                   4274:     return $latex_language_bykey{$key};
                   4275: }
                   4276: 
                   4277: =pod
                   4278: 
1.648     raeburn  4279: =item * &copyrightids() 
1.112     bowersj2 4280: 
                   4281: returns list of all copyrights
                   4282: 
                   4283: =cut
                   4284: 
                   4285: sub copyrightids {
                   4286:     return sort(keys(%cprtag));
                   4287: }
                   4288: 
                   4289: =pod
                   4290: 
1.648     raeburn  4291: =item * &copyrightdescription() 
1.112     bowersj2 4292: 
                   4293: returns description of a specified copyright id
                   4294: 
                   4295: =cut
                   4296: 
                   4297: sub copyrightdescription {
1.166     www      4298:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4299: }
1.197     matthew  4300: 
                   4301: =pod
                   4302: 
1.648     raeburn  4303: =item * &source_copyrightids() 
1.192     taceyjo1 4304: 
                   4305: returns list of all source copyrights
                   4306: 
                   4307: =cut
                   4308: 
                   4309: sub source_copyrightids {
                   4310:     return sort(keys(%scprtag));
                   4311: }
                   4312: 
                   4313: =pod
                   4314: 
1.648     raeburn  4315: =item * &source_copyrightdescription() 
1.192     taceyjo1 4316: 
                   4317: returns description of a specified source copyright id
                   4318: 
                   4319: =cut
                   4320: 
                   4321: sub source_copyrightdescription {
                   4322:     return &mt($scprtag{shift(@_)});
                   4323: }
1.112     bowersj2 4324: 
                   4325: =pod
                   4326: 
1.648     raeburn  4327: =item * &filecategories() 
1.112     bowersj2 4328: 
                   4329: returns list of all file categories
                   4330: 
                   4331: =cut
                   4332: 
                   4333: sub filecategories {
                   4334:     return sort(keys(%category_extensions));
                   4335: }
                   4336: 
                   4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &filecategorytypes() 
1.112     bowersj2 4340: 
                   4341: returns list of file types belonging to a given file
                   4342: category
                   4343: 
                   4344: =cut
                   4345: 
                   4346: sub filecategorytypes {
1.356     albertel 4347:     my ($cat) = @_;
1.1248    raeburn  4348:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4349:         return @{$category_extensions{lc($cat)}};
                   4350:     } else {
                   4351:         return ();
                   4352:     }
1.112     bowersj2 4353: }
                   4354: 
                   4355: =pod
                   4356: 
1.648     raeburn  4357: =item * &fileembstyle() 
1.112     bowersj2 4358: 
                   4359: returns embedding style for a specified file type
                   4360: 
                   4361: =cut
                   4362: 
                   4363: sub fileembstyle {
                   4364:     return $fe{lc(shift(@_))};
1.169     www      4365: }
                   4366: 
1.351     www      4367: sub filemimetype {
                   4368:     return $fm{lc(shift(@_))};
                   4369: }
                   4370: 
1.169     www      4371: 
                   4372: sub filecategoryselect {
                   4373:     my ($name,$value)=@_;
1.189     matthew  4374:     return &select_form($value,$name,
1.970     raeburn  4375:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4376: }
                   4377: 
                   4378: =pod
                   4379: 
1.648     raeburn  4380: =item * &filedescription() 
1.112     bowersj2 4381: 
                   4382: returns description for a specified file type
                   4383: 
                   4384: =cut
                   4385: 
                   4386: sub filedescription {
1.188     matthew  4387:     my $file_description = $fd{lc(shift())};
                   4388:     $file_description =~ s:([\[\]]):~$1:g;
                   4389:     return &mt($file_description);
1.112     bowersj2 4390: }
                   4391: 
                   4392: =pod
                   4393: 
1.648     raeburn  4394: =item * &filedescriptionex() 
1.112     bowersj2 4395: 
                   4396: returns description for a specified file type with
                   4397: extra formatting
                   4398: 
                   4399: =cut
                   4400: 
                   4401: sub filedescriptionex {
                   4402:     my $ex=shift;
1.188     matthew  4403:     my $file_description = $fd{lc($ex)};
                   4404:     $file_description =~ s:([\[\]]):~$1:g;
                   4405:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4406: }
                   4407: 
                   4408: # End of .tab access
                   4409: =pod
                   4410: 
                   4411: =back
                   4412: 
                   4413: =cut
                   4414: 
                   4415: # ------------------------------------------------------------------ File Types
                   4416: sub fileextensions {
                   4417:     return sort(keys(%fe));
                   4418: }
                   4419: 
1.97      www      4420: # ----------------------------------------------------------- Display Languages
                   4421: # returns a hash with all desired display languages
                   4422: #
                   4423: 
                   4424: sub display_languages {
                   4425:     my %languages=();
1.695     raeburn  4426:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4427: 	$languages{$lang}=1;
1.97      www      4428:     }
                   4429:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4430:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4431: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4432: 	    $languages{$lang}=1;
1.97      www      4433:         }
                   4434:     }
                   4435:     return %languages;
1.14      harris41 4436: }
                   4437: 
1.582     albertel 4438: sub languages {
                   4439:     my ($possible_langs) = @_;
1.695     raeburn  4440:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4441:     if (!ref($possible_langs)) {
                   4442: 	if( wantarray ) {
                   4443: 	    return @preferred_langs;
                   4444: 	} else {
                   4445: 	    return $preferred_langs[0];
                   4446: 	}
                   4447:     }
                   4448:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4449:     my @preferred_possibilities;
                   4450:     foreach my $preferred_lang (@preferred_langs) {
                   4451: 	if (exists($possibilities{$preferred_lang})) {
                   4452: 	    push(@preferred_possibilities, $preferred_lang);
                   4453: 	}
                   4454:     }
                   4455:     if( wantarray ) {
                   4456: 	return @preferred_possibilities;
                   4457:     }
                   4458:     return $preferred_possibilities[0];
                   4459: }
                   4460: 
1.742     raeburn  4461: sub user_lang {
                   4462:     my ($touname,$toudom,$fromcid) = @_;
                   4463:     my @userlangs;
                   4464:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4465:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4466:                     $env{'course.'.$fromcid.'.languages'}));
                   4467:     } else {
                   4468:         my %langhash = &getlangs($touname,$toudom);
                   4469:         if ($langhash{'languages'} ne '') {
                   4470:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4471:         } else {
                   4472:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4473:             if ($domdefs{'lang_def'} ne '') {
                   4474:                 @userlangs = ($domdefs{'lang_def'});
                   4475:             }
                   4476:         }
                   4477:     }
                   4478:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4479:     my $user_lh = Apache::localize->get_handle(@languages);
                   4480:     return $user_lh;
                   4481: }
                   4482: 
                   4483: 
1.112     bowersj2 4484: ###############################################################
                   4485: ##               Student Answer Attempts                     ##
                   4486: ###############################################################
                   4487: 
                   4488: =pod
                   4489: 
                   4490: =head1 Alternate Problem Views
                   4491: 
                   4492: =over 4
                   4493: 
1.648     raeburn  4494: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4495:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4496: 
                   4497: Return string with previous attempt on problem. Arguments:
                   4498: 
                   4499: =over 4
                   4500: 
                   4501: =item * $symb: Problem, including path
                   4502: 
                   4503: =item * $username: username of the desired student
                   4504: 
                   4505: =item * $domain: domain of the desired student
1.14      harris41 4506: 
1.112     bowersj2 4507: =item * $course: Course ID
1.14      harris41 4508: 
1.112     bowersj2 4509: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4510:     something
1.14      harris41 4511: 
1.112     bowersj2 4512: =item * $regexp: if string matches this regexp, the string will be
                   4513:     sent to $gradesub
1.14      harris41 4514: 
1.112     bowersj2 4515: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4516: 
1.1199    raeburn  4517: =item * $usec: section of the desired student
                   4518: 
                   4519: =item * $identifier: counter for student (multiple students one problem) or 
                   4520:     problem (one student; whole sequence).
                   4521: 
1.112     bowersj2 4522: =back
1.14      harris41 4523: 
1.112     bowersj2 4524: The output string is a table containing all desired attempts, if any.
1.16      harris41 4525: 
1.112     bowersj2 4526: =cut
1.1       albertel 4527: 
                   4528: sub get_previous_attempt {
1.1199    raeburn  4529:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4530:   my $prevattempts='';
1.43      ng       4531:   no strict 'refs';
1.1       albertel 4532:   if ($symb) {
1.3       albertel 4533:     my (%returnhash)=
                   4534:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4535:     if ($returnhash{'version'}) {
                   4536:       my %lasthash=();
                   4537:       my $version;
                   4538:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4539:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4540:             if ($key =~ /\.rawrndseed$/) {
                   4541:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4542:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4543:             } else {
                   4544:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4545:             }
1.19      harris41 4546:         }
1.1       albertel 4547:       }
1.596     albertel 4548:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4549:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4550:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4551:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4552:       foreach my $key (sort(keys(%lasthash))) {
                   4553: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4554: 	if ($#parts > 0) {
1.31      albertel 4555: 	  my $data=$parts[-1];
1.989     raeburn  4556:           next if ($data eq 'foilorder');
1.31      albertel 4557: 	  pop(@parts);
1.1010    www      4558:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4559:           if ($data eq 'type') {
                   4560:               unless ($showsurv) {
                   4561:                   my $id = join(',',@parts);
                   4562:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4563:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4564:                       $lasthidden{$ign.'.'.$id} = 1;
                   4565:                   }
1.945     raeburn  4566:               }
1.1199    raeburn  4567:               if ($identifier ne '') {
                   4568:                   my $id = join(',',@parts);
                   4569:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4570:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4571:                       $hidestatus{$ign.'.'.$id} = 1;
                   4572:                   }
                   4573:               }
                   4574:           } elsif ($data eq 'regrader') {
                   4575:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4576:                   my $id = join(',',@parts);
                   4577:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4578:               }
1.1010    www      4579:           } 
1.31      albertel 4580: 	} else {
1.41      ng       4581: 	  if ($#parts == 0) {
                   4582: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4583: 	  } else {
                   4584: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4585: 	  }
1.31      albertel 4586: 	}
1.16      harris41 4587:       }
1.596     albertel 4588:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4589:       if ($getattempt eq '') {
1.1199    raeburn  4590:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4591:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4592:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4593:                 foreach my $id (keys(%regraded)) {
                   4594:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4595:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4596:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4597:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4598:                     }
                   4599:                 }
                   4600:             }
1.1200    raeburn  4601:         }
                   4602: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4603:             my (@hidden,@unsolved);
1.945     raeburn  4604:             if (%typeparts) {
                   4605:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4606:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4607:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4608:                         push(@hidden,$id);
1.1199    raeburn  4609:                     } elsif ($identifier ne '') {
                   4610:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4611:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4612:                                 ($hidestatus{$id})) {
1.1200    raeburn  4613:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4614:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4615:                                 push(@{$solved{$id}},$version);
                   4616:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4617:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4618:                                 my $skip;
                   4619:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4620:                                     foreach my $reset (@{$resets{$id}}) {
                   4621:                                         if ($reset > $solved{$id}[-1]) {
                   4622:                                             $skip=1;
                   4623:                                             last;
                   4624:                                         }
                   4625:                                     }
                   4626:                                 }
                   4627:                                 unless ($skip) {
                   4628:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4629:                                     push(@unsolved,$partslist);
                   4630:                                 }
                   4631:                             }
                   4632:                         }
1.945     raeburn  4633:                     }
                   4634:                 }
                   4635:             }
                   4636:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4637:                            '<td>'.&mt('Transaction [_1]',$version);
                   4638:             if (@unsolved) {
                   4639:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4640:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4641:                                  &mt('Hide').'</label></span>';
                   4642:             }
                   4643:             $prevattempts .= '</td>';
1.945     raeburn  4644:             if (@hidden) {
                   4645:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4646:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4647:                     my $hide;
                   4648:                     foreach my $id (@hidden) {
                   4649:                         if ($key =~ /^\Q$id\E/) {
                   4650:                             $hide = 1;
                   4651:                             last;
                   4652:                         }
                   4653:                     }
                   4654:                     if ($hide) {
                   4655:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4656:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4657:                             my $value = &format_previous_attempt_value($key,
                   4658:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4659:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4660:                         } else {
                   4661:                             $prevattempts.='<td>&nbsp;</td>';
                   4662:                         }
                   4663:                     } else {
                   4664:                         if ($key =~ /\./) {
1.1212    raeburn  4665:                             my $value = $returnhash{$version.':'.$key};
                   4666:                             if ($key =~ /\.rndseed$/) {
                   4667:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4668:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4669:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4670:                                 }
                   4671:                             }
                   4672:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4673:                                            '&nbsp;</td>';
1.945     raeburn  4674:                         } else {
                   4675:                             $prevattempts.='<td>&nbsp;</td>';
                   4676:                         }
                   4677:                     }
                   4678:                 }
                   4679:             } else {
                   4680: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4681:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4682:                     my $value = $returnhash{$version.':'.$key};
                   4683:                     if ($key =~ /\.rndseed$/) {
                   4684:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4685:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4686:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4687:                         }
                   4688:                     }
                   4689:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4690:                                    '&nbsp;</td>';
1.945     raeburn  4691: 	        }
                   4692:             }
                   4693: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4694: 	 }
1.1       albertel 4695:       }
1.945     raeburn  4696:       my @currhidden = keys(%lasthidden);
1.596     albertel 4697:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4698:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4699:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4700:           if (%typeparts) {
                   4701:               my $hidden;
                   4702:               foreach my $id (@currhidden) {
                   4703:                   if ($key =~ /^\Q$id\E/) {
                   4704:                       $hidden = 1;
                   4705:                       last;
                   4706:                   }
                   4707:               }
                   4708:               if ($hidden) {
                   4709:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4710:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4711:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4712:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4713:                           $value = &$gradesub($value);
                   4714:                       }
1.1173    kruse    4715:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4716:                   } else {
                   4717:                       $prevattempts.='<td>&nbsp;</td>';
                   4718:                   }
                   4719:               } else {
                   4720:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4721:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4722:                       $value = &$gradesub($value);
                   4723:                   }
1.1173    kruse    4724:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4725:               }
                   4726:           } else {
                   4727: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4728: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4729:                   $value = &$gradesub($value);
                   4730:               }
1.1173    kruse    4731: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4732:           }
1.16      harris41 4733:       }
1.596     albertel 4734:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4735:     } else {
1.1305    raeburn  4736:       my $msg;
                   4737:       if ($symb =~ /ext\.tool$/) {
                   4738:           $msg = &mt('No grade passed back.');
                   4739:       } else {
                   4740:           $msg = &mt('Nothing submitted - no attempts.');
                   4741:       }
1.596     albertel 4742:       $prevattempts=
                   4743: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4744: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4745: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4746:     }
                   4747:   } else {
1.596     albertel 4748:     $prevattempts=
                   4749: 	  &start_data_table().&start_data_table_row().
                   4750: 	  '<td>'.&mt('No data.').'</td>'.
                   4751: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4752:   }
1.10      albertel 4753: }
                   4754: 
1.581     albertel 4755: sub format_previous_attempt_value {
                   4756:     my ($key,$value) = @_;
1.1011    www      4757:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4758:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4759:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4760:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4761:     } elsif ($key =~ /answerstring$/) {
                   4762:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4763:         my @answer = %answers;
                   4764:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4765:         my @anskeys = sort(keys(%answers));
                   4766:         if (@anskeys == 1) {
                   4767:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4768:             if ($answer =~ m{\0}) {
                   4769:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4770:             }
                   4771:             my $tag_internal_answer_name = 'INTERNAL';
                   4772:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4773:                 $value = $answer; 
                   4774:             } else {
                   4775:                 $value = $anskeys[0].'='.$answer;
                   4776:             }
                   4777:         } else {
                   4778:             foreach my $ans (@anskeys) {
                   4779:                 my $answer = $answers{$ans};
1.1001    raeburn  4780:                 if ($answer =~ m{\0}) {
                   4781:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4782:                 }
                   4783:                 $value .=  $ans.'='.$answer.'<br />';;
                   4784:             } 
                   4785:         }
1.581     albertel 4786:     } else {
1.1173    kruse    4787:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4788:     }
                   4789:     return $value;
                   4790: }
                   4791: 
                   4792: 
1.107     albertel 4793: sub relative_to_absolute {
                   4794:     my ($url,$output)=@_;
                   4795:     my $parser=HTML::TokeParser->new(\$output);
                   4796:     my $token;
                   4797:     my $thisdir=$url;
                   4798:     my @rlinks=();
                   4799:     while ($token=$parser->get_token) {
                   4800: 	if ($token->[0] eq 'S') {
                   4801: 	    if ($token->[1] eq 'a') {
                   4802: 		if ($token->[2]->{'href'}) {
                   4803: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4804: 		}
                   4805: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4806: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4807: 	    } elsif ($token->[1] eq 'base') {
                   4808: 		$thisdir=$token->[2]->{'href'};
                   4809: 	    }
                   4810: 	}
                   4811:     }
                   4812:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4813:     foreach my $link (@rlinks) {
1.726     raeburn  4814: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4815: 		($link=~/^\//) ||
                   4816: 		($link=~/^javascript:/i) ||
                   4817: 		($link=~/^mailto:/i) ||
                   4818: 		($link=~/^\#/)) {
                   4819: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4820: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4821: 	}
                   4822:     }
                   4823: # -------------------------------------------------- Deal with Applet codebases
                   4824:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4825:     return $output;
                   4826: }
                   4827: 
1.112     bowersj2 4828: =pod
                   4829: 
1.648     raeburn  4830: =item * &get_student_view()
1.112     bowersj2 4831: 
                   4832: show a snapshot of what student was looking at
                   4833: 
                   4834: =cut
                   4835: 
1.10      albertel 4836: sub get_student_view {
1.186     albertel 4837:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4838:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4839:   my (%form);
1.10      albertel 4840:   my @elements=('symb','courseid','domain','username');
                   4841:   foreach my $element (@elements) {
1.186     albertel 4842:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4843:   }
1.186     albertel 4844:   if (defined($moreenv)) {
                   4845:       %form=(%form,%{$moreenv});
                   4846:   }
1.236     albertel 4847:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4848:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4849:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4850:       $feedurl =~ s{^/adm/wrapper}{};
                   4851:   }
1.650     www      4852:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4853:   $userview=~s/\<body[^\>]*\>//gi;
                   4854:   $userview=~s/\<\/body\>//gi;
                   4855:   $userview=~s/\<html\>//gi;
                   4856:   $userview=~s/\<\/html\>//gi;
                   4857:   $userview=~s/\<head\>//gi;
                   4858:   $userview=~s/\<\/head\>//gi;
                   4859:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4860:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4861:   if (wantarray) {
                   4862:      return ($userview,$response);
                   4863:   } else {
                   4864:      return $userview;
                   4865:   }
                   4866: }
                   4867: 
                   4868: sub get_student_view_with_retries {
                   4869:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4870: 
                   4871:     my $ok = 0;                 # True if we got a good response.
                   4872:     my $content;
                   4873:     my $response;
                   4874: 
                   4875:     # Try to get the student_view done. within the retries count:
                   4876:     
                   4877:     do {
                   4878:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4879:          $ok      = $response->is_success;
                   4880:          if (!$ok) {
                   4881:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4882:          }
                   4883:          $retries--;
                   4884:     } while (!$ok && ($retries > 0));
                   4885:     
                   4886:     if (!$ok) {
                   4887:        $content = '';          # On error return an empty content.
                   4888:     }
1.651     www      4889:     if (wantarray) {
                   4890:        return ($content, $response);
                   4891:     } else {
                   4892:        return $content;
                   4893:     }
1.11      albertel 4894: }
                   4895: 
1.1349    raeburn  4896: sub css_links {
                   4897:     my ($currsymb,$level) = @_;
                   4898:     my ($links,@symbs,%cssrefs,%httpref);
                   4899:     if ($level eq 'map') {
                   4900:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4901:         if (ref($navmap)) {
                   4902:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4903:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4904:             foreach my $res (@resources) {
                   4905:                 if (ref($res) && $res->symb()) {
                   4906:                     push(@symbs,$res->symb());
                   4907:                 }
                   4908:             }
                   4909:         }
                   4910:     } else {
                   4911:         @symbs = ($currsymb);
                   4912:     }
                   4913:     foreach my $symb (@symbs) {
                   4914:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4915:         if ($css_href =~ /\S/) {
                   4916:             unless ($css_href =~ m{https?://}) {
                   4917:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4918:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4919:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4920:                 unless ($css_href =~ m{^/}) {
                   4921:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4922:                 }
                   4923:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4924:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4925:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4926:                         my $thisurl = $proburl;
                   4927:                         if ($env{'httpref.'.$proburl}) {
                   4928:                             $thisurl = $env{'httpref.'.$proburl};
                   4929:                         }
                   4930:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4931:                     }
                   4932:                 }
                   4933:             }
                   4934:             $cssrefs{$css_href} = 1;
                   4935:         }
                   4936:     }
                   4937:     if (keys(%httpref)) {
                   4938:         &Apache::lonnet::appenv(\%httpref);
                   4939:     }
                   4940:     if (keys(%cssrefs)) {
                   4941:         foreach my $css_href (keys(%cssrefs)) {
                   4942:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4943:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4944:         }
                   4945:     }
                   4946:     return $links;
                   4947: }
                   4948: 
1.112     bowersj2 4949: =pod
                   4950: 
1.648     raeburn  4951: =item * &get_student_answers() 
1.112     bowersj2 4952: 
                   4953: show a snapshot of how student was answering problem
                   4954: 
                   4955: =cut
                   4956: 
1.11      albertel 4957: sub get_student_answers {
1.100     sakharuk 4958:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4959:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4960:   my (%moreenv);
1.11      albertel 4961:   my @elements=('symb','courseid','domain','username');
                   4962:   foreach my $element (@elements) {
1.186     albertel 4963:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4964:   }
1.186     albertel 4965:   $moreenv{'grade_target'}='answer';
                   4966:   %moreenv=(%form,%moreenv);
1.497     raeburn  4967:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4968:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4969:   return $userview;
1.1       albertel 4970: }
1.116     albertel 4971: 
                   4972: =pod
                   4973: 
                   4974: =item * &submlink()
                   4975: 
1.242     albertel 4976: Inputs: $text $uname $udom $symb $target
1.116     albertel 4977: 
                   4978: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4979: 
                   4980: =cut
                   4981: 
                   4982: ###############################################
                   4983: sub submlink {
1.242     albertel 4984:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4985:     if (!($uname && $udom)) {
                   4986: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4987: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4988: 	if (!$symb) { $symb=$cursymb; }
                   4989:     }
1.254     matthew  4990:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4991:     $symb=&escape($symb);
1.960     bisitz   4992:     if ($target) { $target=" target=\"$target\""; }
                   4993:     return
                   4994:         '<a href="/adm/grades?command=submission'.
                   4995:         '&amp;symb='.$symb.
                   4996:         '&amp;student='.$uname.
                   4997:         '&amp;userdom='.$udom.'"'.
                   4998:         $target.'>'.$text.'</a>';
1.242     albertel 4999: }
                   5000: ##############################################
                   5001: 
                   5002: =pod
                   5003: 
                   5004: =item * &pgrdlink()
                   5005: 
                   5006: Inputs: $text $uname $udom $symb $target
                   5007: 
                   5008: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5009: 
                   5010: =cut
                   5011: 
                   5012: ###############################################
                   5013: sub pgrdlink {
                   5014:     my $link=&submlink(@_);
                   5015:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5016:     return $link;
                   5017: }
                   5018: ##############################################
                   5019: 
                   5020: =pod
                   5021: 
                   5022: =item * &pprmlink()
                   5023: 
                   5024: Inputs: $text $uname $udom $symb $target
                   5025: 
                   5026: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5027: student and a specific resource
1.242     albertel 5028: 
                   5029: =cut
                   5030: 
                   5031: ###############################################
                   5032: sub pprmlink {
                   5033:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5034:     if (!($uname && $udom)) {
                   5035: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5036: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5037: 	if (!$symb) { $symb=$cursymb; }
                   5038:     }
1.254     matthew  5039:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5040:     $symb=&escape($symb);
1.242     albertel 5041:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5042:     return '<a href="/adm/parmset?command=set&amp;'.
                   5043: 	'symb='.$symb.'&amp;uname='.$uname.
                   5044: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5045: }
                   5046: ##############################################
1.37      matthew  5047: 
1.112     bowersj2 5048: =pod
                   5049: 
                   5050: =back
                   5051: 
                   5052: =cut
                   5053: 
1.37      matthew  5054: ###############################################
1.51      www      5055: 
                   5056: 
                   5057: sub timehash {
1.687     raeburn  5058:     my ($thistime) = @_;
                   5059:     my $timezone = &Apache::lonlocal::gettimezone();
                   5060:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5061:                      ->set_time_zone($timezone);
                   5062:     my $wday = $dt->day_of_week();
                   5063:     if ($wday == 7) { $wday = 0; }
                   5064:     return ( 'second' => $dt->second(),
                   5065:              'minute' => $dt->minute(),
                   5066:              'hour'   => $dt->hour(),
                   5067:              'day'     => $dt->day_of_month(),
                   5068:              'month'   => $dt->month(),
                   5069:              'year'    => $dt->year(),
                   5070:              'weekday' => $wday,
                   5071:              'dayyear' => $dt->day_of_year(),
                   5072:              'dlsav'   => $dt->is_dst() );
1.51      www      5073: }
                   5074: 
1.370     www      5075: sub utc_string {
                   5076:     my ($date)=@_;
1.371     www      5077:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5078: }
                   5079: 
1.51      www      5080: sub maketime {
                   5081:     my %th=@_;
1.687     raeburn  5082:     my ($epoch_time,$timezone,$dt);
                   5083:     $timezone = &Apache::lonlocal::gettimezone();
                   5084:     eval {
                   5085:         $dt = DateTime->new( year   => $th{'year'},
                   5086:                              month  => $th{'month'},
                   5087:                              day    => $th{'day'},
                   5088:                              hour   => $th{'hour'},
                   5089:                              minute => $th{'minute'},
                   5090:                              second => $th{'second'},
                   5091:                              time_zone => $timezone,
                   5092:                          );
                   5093:     };
                   5094:     if (!$@) {
                   5095:         $epoch_time = $dt->epoch;
                   5096:         if ($epoch_time) {
                   5097:             return $epoch_time;
                   5098:         }
                   5099:     }
1.51      www      5100:     return POSIX::mktime(
                   5101:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5102:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5103: }
                   5104: 
                   5105: #########################################
1.51      www      5106: 
                   5107: sub findallcourses {
1.482     raeburn  5108:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5109:     my %roles;
                   5110:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5111:     my %courses;
1.51      www      5112:     my $now=time;
1.482     raeburn  5113:     if (!defined($uname)) {
                   5114:         $uname = $env{'user.name'};
                   5115:     }
                   5116:     if (!defined($udom)) {
                   5117:         $udom = $env{'user.domain'};
                   5118:     }
                   5119:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5120:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5121:         if (!%roles) {
                   5122:             %roles = (
                   5123:                        cc => 1,
1.907     raeburn  5124:                        co => 1,
1.482     raeburn  5125:                        in => 1,
                   5126:                        ep => 1,
                   5127:                        ta => 1,
                   5128:                        cr => 1,
                   5129:                        st => 1,
                   5130:              );
                   5131:         }
                   5132:         foreach my $entry (keys(%roleshash)) {
                   5133:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5134:             if ($trole =~ /^cr/) { 
                   5135:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5136:             } else {
                   5137:                 next if (!exists($roles{$trole}));
                   5138:             }
                   5139:             if ($tend) {
                   5140:                 next if ($tend < $now);
                   5141:             }
                   5142:             if ($tstart) {
                   5143:                 next if ($tstart > $now);
                   5144:             }
1.1058    raeburn  5145:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5146:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5147:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5148:             if ($secpart eq '') {
                   5149:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5150:                 $sec = 'none';
1.1058    raeburn  5151:                 $value .= $cnum.'/';
1.482     raeburn  5152:             } else {
                   5153:                 $cnum = $cnumpart;
                   5154:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5155:                 $value .= $cnum.'/'.$sec;
                   5156:             }
                   5157:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5158:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5159:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5160:                 }
                   5161:             } else {
                   5162:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5163:             }
1.482     raeburn  5164:         }
                   5165:     } else {
                   5166:         foreach my $key (keys(%env)) {
1.483     albertel 5167: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5168:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5169: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5170: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5171: 	        next if (%roles && !exists($roles{$role}));
                   5172: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5173:                 my $active=1;
                   5174:                 if ($starttime) {
                   5175: 		    if ($now<$starttime) { $active=0; }
                   5176:                 }
                   5177:                 if ($endtime) {
                   5178:                     if ($now>$endtime) { $active=0; }
                   5179:                 }
                   5180:                 if ($active) {
1.1058    raeburn  5181:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5182:                     if ($sec eq '') {
                   5183:                         $sec = 'none';
1.1058    raeburn  5184:                     } else {
                   5185:                         $value .= $sec;
                   5186:                     }
                   5187:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5188:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5189:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5190:                         }
                   5191:                     } else {
                   5192:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5193:                     }
1.474     raeburn  5194:                 }
                   5195:             }
1.51      www      5196:         }
                   5197:     }
1.474     raeburn  5198:     return %courses;
1.51      www      5199: }
1.37      matthew  5200: 
1.54      www      5201: ###############################################
1.474     raeburn  5202: 
                   5203: sub blockcheck {
1.1347    raeburn  5204:     my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  5205: 
1.1189    raeburn  5206:     if (defined($udom) && defined($uname)) {
                   5207:         # If uname and udom are for a course, check for blocks in the course.
                   5208:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5209:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5210:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5211:             return ($startblock,$endblock,$triggerblock);
                   5212:         }
                   5213:     } else {
1.490     raeburn  5214:         $udom = $env{'user.domain'};
                   5215:         $uname = $env{'user.name'};
                   5216:     }
                   5217: 
1.502     raeburn  5218:     my $startblock = 0;
                   5219:     my $endblock = 0;
1.1062    raeburn  5220:     my $triggerblock = '';
1.482     raeburn  5221:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5222: 
1.490     raeburn  5223:     # If uname is for a user, and activity is course-specific, i.e.,
                   5224:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5225: 
1.490     raeburn  5226:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5227:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5228:          $activity eq 'search' || $activity eq 'reinit' ||
                   5229:          $activity eq 'alert') &&
1.1189    raeburn  5230:         ($env{'request.course.id'})) {
1.490     raeburn  5231:         foreach my $key (keys(%live_courses)) {
                   5232:             if ($key ne $env{'request.course.id'}) {
                   5233:                 delete($live_courses{$key});
                   5234:             }
                   5235:         }
                   5236:     }
                   5237: 
                   5238:     my $otheruser = 0;
                   5239:     my %own_courses;
                   5240:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5241:         # Resource belongs to user other than current user.
                   5242:         $otheruser = 1;
                   5243:         # Gather courses for current user
                   5244:         %own_courses = 
                   5245:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5246:     }
                   5247: 
                   5248:     # Gather active course roles - course coordinator, instructor, 
                   5249:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5250: 
                   5251:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5252:         my ($cdom,$cnum);
                   5253:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5254:             $cdom = $env{'course.'.$course.'.domain'};
                   5255:             $cnum = $env{'course.'.$course.'.num'};
                   5256:         } else {
1.490     raeburn  5257:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5258:         }
                   5259:         my $no_ownblock = 0;
                   5260:         my $no_userblock = 0;
1.533     raeburn  5261:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5262:             # Check if current user has 'evb' priv for this
                   5263:             if (defined($own_courses{$course})) {
                   5264:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5265:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5266:                     if ($sec ne 'none') {
                   5267:                         $checkrole .= '/'.$sec;
                   5268:                     }
                   5269:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5270:                         $no_ownblock = 1;
                   5271:                         last;
                   5272:                     }
                   5273:                 }
                   5274:             }
                   5275:             # if they have 'evb' priv and are currently not playing student
                   5276:             next if (($no_ownblock) &&
                   5277:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5278:         }
1.474     raeburn  5279:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5280:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5281:             if ($sec ne 'none') {
1.482     raeburn  5282:                 $checkrole .= '/'.$sec;
1.474     raeburn  5283:             }
1.490     raeburn  5284:             if ($otheruser) {
                   5285:                 # Resource belongs to user other than current user.
                   5286:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5287:                 my (%allroles,%userroles);
                   5288:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5289:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5290:                         my ($trole,$tdom,$tnum,$tsec);
                   5291:                         if ($entry =~ /^cr/) {
                   5292:                             ($trole,$tdom,$tnum,$tsec) = 
                   5293:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5294:                         } else {
                   5295:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5296:                         }
                   5297:                         my ($spec,$area,$trest);
                   5298:                         $area = '/'.$tdom.'/'.$tnum;
                   5299:                         $trest = $tnum;
                   5300:                         if ($tsec ne '') {
                   5301:                             $area .= '/'.$tsec;
                   5302:                             $trest .= '/'.$tsec;
                   5303:                         }
                   5304:                         $spec = $trole.'.'.$area;
                   5305:                         if ($trole =~ /^cr/) {
                   5306:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5307:                                                               $tdom,$spec,$trest,$area);
                   5308:                         } else {
                   5309:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5310:                                                                 $tdom,$spec,$trest,$area);
                   5311:                         }
                   5312:                     }
1.1276    raeburn  5313:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5314:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5315:                         if ($1) {
                   5316:                             $no_userblock = 1;
                   5317:                             last;
                   5318:                         }
1.486     raeburn  5319:                     }
                   5320:                 }
1.490     raeburn  5321:             } else {
                   5322:                 # Resource belongs to current user
                   5323:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5324:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5325:                     $no_ownblock = 1;
                   5326:                     last;
                   5327:                 }
1.474     raeburn  5328:             }
                   5329:         }
                   5330:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5331:         next if (($no_ownblock) &&
1.491     albertel 5332:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5333:         next if ($no_userblock);
1.474     raeburn  5334: 
1.1303    raeburn  5335:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5336:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5337: 
1.1062    raeburn  5338:         my ($start,$end,$trigger) = 
1.1347    raeburn  5339:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5340:         if (($start != 0) && 
                   5341:             (($startblock == 0) || ($startblock > $start))) {
                   5342:             $startblock = $start;
1.1062    raeburn  5343:             if ($trigger ne '') {
                   5344:                 $triggerblock = $trigger;
                   5345:             }
1.502     raeburn  5346:         }
                   5347:         if (($end != 0)  &&
                   5348:             (($endblock == 0) || ($endblock < $end))) {
                   5349:             $endblock = $end;
1.1062    raeburn  5350:             if ($trigger ne '') {
                   5351:                 $triggerblock = $trigger;
                   5352:             }
1.502     raeburn  5353:         }
1.490     raeburn  5354:     }
1.1062    raeburn  5355:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5356: }
                   5357: 
                   5358: sub get_blocks {
1.1347    raeburn  5359:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5360:     my $startblock = 0;
                   5361:     my $endblock = 0;
1.1062    raeburn  5362:     my $triggerblock = '';
1.490     raeburn  5363:     my $course = $cdom.'_'.$cnum;
                   5364:     $setters->{$course} = {};
                   5365:     $setters->{$course}{'staff'} = [];
                   5366:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5367:     $setters->{$course}{'triggers'} = [];
                   5368:     my (@blockers,%triggered);
                   5369:     my $now = time;
                   5370:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5371:     if ($activity eq 'docs') {
1.1348    raeburn  5372:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5373:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5374:             $blocked = 1;
                   5375:             $nosymbcache = 1;
1.1348    raeburn  5376:             $noenccheck = 1;
1.1347    raeburn  5377:         }
1.1348    raeburn  5378:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5379:         foreach my $block (@blockers) {
                   5380:             if ($block =~ /^firstaccess____(.+)$/) {
                   5381:                 my $item = $1;
                   5382:                 my $type = 'map';
                   5383:                 my $timersymb = $item;
                   5384:                 if ($item eq 'course') {
                   5385:                     $type = 'course';
                   5386:                 } elsif ($item =~ /___\d+___/) {
                   5387:                     $type = 'resource';
                   5388:                 } else {
                   5389:                     $timersymb = &Apache::lonnet::symbread($item);
                   5390:                 }
                   5391:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5392:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5393:                 $triggered{$block} = {
                   5394:                                        start => $start,
                   5395:                                        end   => $end,
                   5396:                                        type  => $type,
                   5397:                                      };
                   5398:             }
                   5399:         }
                   5400:     } else {
                   5401:         foreach my $block (keys(%commblocks)) {
                   5402:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5403:                 my ($start,$end) = ($1,$2);
                   5404:                 if ($start <= time && $end >= time) {
                   5405:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5406:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5407:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5408:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5409:                                     push(@blockers,$block);
                   5410:                                 }
                   5411:                             }
                   5412:                         }
                   5413:                     }
                   5414:                 }
                   5415:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5416:                 my $item = $1;
                   5417:                 my $timersymb = $item; 
                   5418:                 my $type = 'map';
                   5419:                 if ($item eq 'course') {
                   5420:                     $type = 'course';
                   5421:                 } elsif ($item =~ /___\d+___/) {
                   5422:                     $type = 'resource';
                   5423:                 } else {
                   5424:                     $timersymb = &Apache::lonnet::symbread($item);
                   5425:                 }
                   5426:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5427:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5428:                 if ($start && $end) {
                   5429:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5430:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5431:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5432:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5433:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5434:                                         push(@blockers,$block);
                   5435:                                         $triggered{$block} = {
                   5436:                                                                start => $start,
                   5437:                                                                end   => $end,
                   5438:                                                                type  => $type,
                   5439:                                                              };
                   5440:                                     }
                   5441:                                 }
                   5442:                             }
1.1062    raeburn  5443:                         }
                   5444:                     }
1.490     raeburn  5445:                 }
1.1062    raeburn  5446:             }
                   5447:         }
                   5448:     }
                   5449:     foreach my $blocker (@blockers) {
                   5450:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5451:             &parse_block_record($commblocks{$blocker});
                   5452:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5453:         my ($start,$end,$triggertype);
                   5454:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5455:             ($start,$end) = ($1,$2);
                   5456:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5457:             $start = $triggered{$blocker}{'start'};
                   5458:             $end = $triggered{$blocker}{'end'};
                   5459:             $triggertype = $triggered{$blocker}{'type'};
                   5460:         }
                   5461:         if ($start) {
                   5462:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5463:             if ($triggertype) {
                   5464:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5465:             } else {
                   5466:                 push(@{$$setters{$course}{'triggers'}},0);
                   5467:             }
                   5468:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5469:                 $startblock = $start;
                   5470:                 if ($triggertype) {
                   5471:                     $triggerblock = $blocker;
1.474     raeburn  5472:                 }
                   5473:             }
1.1062    raeburn  5474:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5475:                $endblock = $end;
                   5476:                if ($triggertype) {
                   5477:                    $triggerblock = $blocker;
                   5478:                }
                   5479:             }
1.474     raeburn  5480:         }
                   5481:     }
1.1062    raeburn  5482:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5483: }
                   5484: 
                   5485: sub parse_block_record {
                   5486:     my ($record) = @_;
                   5487:     my ($setuname,$setudom,$title,$blocks);
                   5488:     if (ref($record) eq 'HASH') {
                   5489:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5490:         $title = &unescape($record->{'event'});
                   5491:         $blocks = $record->{'blocks'};
                   5492:     } else {
                   5493:         my @data = split(/:/,$record,3);
                   5494:         if (scalar(@data) eq 2) {
                   5495:             $title = $data[1];
                   5496:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5497:         } else {
                   5498:             ($setuname,$setudom,$title) = @data;
                   5499:         }
                   5500:         $blocks = { 'com' => 'on' };
                   5501:     }
                   5502:     return ($setuname,$setudom,$title,$blocks);
                   5503: }
                   5504: 
1.854     kalberla 5505: sub blocking_status {
1.1347    raeburn  5506:     my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5507:     my %setters;
1.890     droeschl 5508: 
1.1061    raeburn  5509: # check for active blocking
1.1062    raeburn  5510:     my ($startblock,$endblock,$triggerblock) = 
1.1347    raeburn  5511:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5512:     my $blocked = 0;
                   5513:     if ($startblock && $endblock) {
                   5514:         $blocked = 1;
                   5515:     }
1.890     droeschl 5516: 
1.1061    raeburn  5517: # caller just wants to know whether a block is active
                   5518:     if (!wantarray) { return $blocked; }
                   5519: 
                   5520: # build a link to a popup window containing the details
                   5521:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5522: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5523:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5524:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5525:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5526:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5527:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5528:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5529:         if ($symb) {
                   5530:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5531:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5532:         }
1.1062    raeburn  5533:     }
1.1061    raeburn  5534: 
                   5535:     my $output .= <<'END_MYBLOCK';
                   5536: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5537:     var options = "width=" + w + ",height=" + h + ",";
                   5538:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5539:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5540:     var newWin = window.open(url, wdwName, options);
                   5541:     newWin.focus();
                   5542: }
1.890     droeschl 5543: END_MYBLOCK
1.854     kalberla 5544: 
1.1061    raeburn  5545:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5546:   
1.1061    raeburn  5547:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5548:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5549:     my $class = 'LC_comblock';
1.1062    raeburn  5550:     if ($activity eq 'docs') {
                   5551:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5552:         $class = '';
1.1063    raeburn  5553:     } elsif ($activity eq 'printout') {
                   5554:         $text = &mt('Printing Blocked');
1.1232    raeburn  5555:     } elsif ($activity eq 'passwd') {
                   5556:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5557:     } elsif ($activity eq 'grades') {
                   5558:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5559:     } elsif ($activity eq 'search') {
                   5560:         $text = &mt('Search Blocked');
1.1282    raeburn  5561:     } elsif ($activity eq 'alert') {
                   5562:         $text = &mt('Checking Critical Messages Blocked');
                   5563:     } elsif ($activity eq 'reinit') {
                   5564:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5565:     } elsif ($activity eq 'about') {
                   5566:         $text = &mt('Access to User Information Pages Blocked');
1.1062    raeburn  5567:     }
1.1061    raeburn  5568:     $output .= <<"END_BLOCK";
1.1217    raeburn  5569: <div class='$class'>
1.869     kalberla 5570:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5571:   title='$text'>
                   5572:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5573:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5574:   title='$text'>$text</a>
1.867     kalberla 5575: </div>
                   5576: 
                   5577: END_BLOCK
1.474     raeburn  5578: 
1.1061    raeburn  5579:     return ($blocked, $output);
1.854     kalberla 5580: }
1.490     raeburn  5581: 
1.60      matthew  5582: ###############################################
                   5583: 
1.682     raeburn  5584: sub check_ip_acc {
1.1201    raeburn  5585:     my ($acc,$clientip)=@_;
1.682     raeburn  5586:     &Apache::lonxml::debug("acc is $acc");
                   5587:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5588:         return 1;
                   5589:     }
1.1339    raeburn  5590:     my ($ip,$allowed);
                   5591:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5592:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5593:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5594:     } else {
1.1350    raeburn  5595:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5596:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5597:     }
1.682     raeburn  5598: 
                   5599:     my $name;
1.1219    raeburn  5600:     my %access = (
                   5601:                      allowfrom => 1,
                   5602:                      denyfrom  => 0,
                   5603:                  );
                   5604:     my @allows;
                   5605:     my @denies;
                   5606:     foreach my $item (split(',',$acc)) {
                   5607:         $item =~ s/^\s*//;
                   5608:         $item =~ s/\s*$//;
                   5609:         my $pattern;
                   5610:         if ($item =~ /^\!(.+)$/) {
                   5611:             push(@denies,$1);
                   5612:         } else {
                   5613:             push(@allows,$item);
                   5614:         }
                   5615:    }
                   5616:    my $numdenies = scalar(@denies);
                   5617:    my $numallows = scalar(@allows);
                   5618:    my $count = 0;
                   5619:    foreach my $pattern (@denies,@allows) {
                   5620:         $count ++; 
                   5621:         my $acctype = 'allowfrom';
                   5622:         if ($count <= $numdenies) {
                   5623:             $acctype = 'denyfrom';
                   5624:         }
1.682     raeburn  5625:         if ($pattern =~ /\*$/) {
                   5626:             #35.8.*
                   5627:             $pattern=~s/\*//;
1.1219    raeburn  5628:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5629:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5630:             #35.8.3.[34-56]
                   5631:             my $low=$2;
                   5632:             my $high=$3;
                   5633:             $pattern=$1;
                   5634:             if ($ip =~ /^\Q$pattern\E/) {
                   5635:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5636:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5637:             }
                   5638:         } elsif ($pattern =~ /^\*/) {
                   5639:             #*.msu.edu
                   5640:             $pattern=~s/\*//;
                   5641:             if (!defined($name)) {
                   5642:                 use Socket;
                   5643:                 my $netaddr=inet_aton($ip);
                   5644:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5645:             }
1.1219    raeburn  5646:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5647:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5648:             #127.0.0.1
1.1219    raeburn  5649:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5650:         } else {
                   5651:             #some.name.com
                   5652:             if (!defined($name)) {
                   5653:                 use Socket;
                   5654:                 my $netaddr=inet_aton($ip);
                   5655:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5656:             }
1.1219    raeburn  5657:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5658:         }
                   5659:         if ($allowed =~ /^(0|1)$/) { last; }
                   5660:     }
                   5661:     if ($allowed eq '') {
                   5662:         if ($numdenies && !$numallows) {
                   5663:             $allowed = 1;
                   5664:         } else {
                   5665:             $allowed = 0;
1.682     raeburn  5666:         }
                   5667:     }
                   5668:     return $allowed;
                   5669: }
                   5670: 
                   5671: ###############################################
                   5672: 
1.60      matthew  5673: =pod
                   5674: 
1.112     bowersj2 5675: =head1 Domain Template Functions
                   5676: 
                   5677: =over 4
                   5678: 
                   5679: =item * &determinedomain()
1.60      matthew  5680: 
                   5681: Inputs: $domain (usually will be undef)
                   5682: 
1.63      www      5683: Returns: Determines which domain should be used for designs
1.60      matthew  5684: 
                   5685: =cut
1.54      www      5686: 
1.60      matthew  5687: ###############################################
1.63      www      5688: sub determinedomain {
                   5689:     my $domain=shift;
1.531     albertel 5690:     if (! $domain) {
1.60      matthew  5691:         # Determine domain if we have not been given one
1.893     raeburn  5692:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5693:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5694:         if ($env{'request.role.domain'}) { 
                   5695:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5696:         }
                   5697:     }
1.63      www      5698:     return $domain;
                   5699: }
                   5700: ###############################################
1.517     raeburn  5701: 
1.518     albertel 5702: sub devalidate_domconfig_cache {
                   5703:     my ($udom)=@_;
                   5704:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5705: }
                   5706: 
                   5707: # ---------------------- Get domain configuration for a domain
                   5708: sub get_domainconf {
                   5709:     my ($udom) = @_;
                   5710:     my $cachetime=1800;
                   5711:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5712:     if (defined($cached)) { return %{$result}; }
                   5713: 
                   5714:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5715: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5716:     my (%designhash,%legacy);
1.518     albertel 5717:     if (keys(%domconfig) > 0) {
                   5718:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5719:             if (keys(%{$domconfig{'login'}})) {
                   5720:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5721:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5722:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5723:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5724:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5725:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5726:                                         if ($key eq 'loginvia') {
                   5727:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5728:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5729:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5730:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5731: 
                   5732:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5733:                                                 } else {
                   5734:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5735:                                                 }
1.948     raeburn  5736:                                             }
1.1208    raeburn  5737:                                         } elsif ($key eq 'headtag') {
                   5738:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5739:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5740:                                             }
1.946     raeburn  5741:                                         }
1.1208    raeburn  5742:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5743:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5744:                                         }
1.946     raeburn  5745:                                     }
                   5746:                                 }
                   5747:                             }
1.1366    raeburn  5748:                         } elsif ($key eq 'saml') {
                   5749:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5750:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5751:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5752:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
                   5753:                                         foreach my $item ('text','img','alt','url','title','notsso') {
                   5754:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5755:                                         }
                   5756:                                     }
                   5757:                                 }
                   5758:                             }
1.946     raeburn  5759:                         } else {
                   5760:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5761:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5762:                                     $domconfig{'login'}{$key}{$img};
                   5763:                             }
1.699     raeburn  5764:                         }
                   5765:                     } else {
                   5766:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5767:                     }
1.632     raeburn  5768:                 }
                   5769:             } else {
                   5770:                 $legacy{'login'} = 1;
1.518     albertel 5771:             }
1.632     raeburn  5772:         } else {
                   5773:             $legacy{'login'} = 1;
1.518     albertel 5774:         }
                   5775:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5776:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5777:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5778:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5779:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5780:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5781:                         }
1.518     albertel 5782:                     }
                   5783:                 }
1.632     raeburn  5784:             } else {
                   5785:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5786:             }
1.632     raeburn  5787:         } else {
                   5788:             $legacy{'rolecolors'} = 1;
1.518     albertel 5789:         }
1.948     raeburn  5790:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5791:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5792:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5793:             }
                   5794:         }
1.632     raeburn  5795:         if (keys(%legacy) > 0) {
                   5796:             my %legacyhash = &get_legacy_domconf($udom);
                   5797:             foreach my $item (keys(%legacyhash)) {
                   5798:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5799:                     if ($legacy{'login'}) { 
                   5800:                         $designhash{$item} = $legacyhash{$item};
                   5801:                     }
                   5802:                 } else {
                   5803:                     if ($legacy{'rolecolors'}) {
                   5804:                         $designhash{$item} = $legacyhash{$item};
                   5805:                     }
1.518     albertel 5806:                 }
                   5807:             }
                   5808:         }
1.632     raeburn  5809:     } else {
                   5810:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5811:     }
                   5812:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5813: 				  $cachetime);
                   5814:     return %designhash;
                   5815: }
                   5816: 
1.632     raeburn  5817: sub get_legacy_domconf {
                   5818:     my ($udom) = @_;
                   5819:     my %legacyhash;
                   5820:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5821:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5822:     if (-e $designfile) {
1.1317    raeburn  5823:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5824:             while (my $line = <$fh>) {
                   5825:                 next if ($line =~ /^\#/);
                   5826:                 chomp($line);
                   5827:                 my ($key,$val)=(split(/\=/,$line));
                   5828:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5829:             }
                   5830:             close($fh);
                   5831:         }
                   5832:     }
1.1026    raeburn  5833:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5834:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5835:     }
                   5836:     return %legacyhash;
                   5837: }
                   5838: 
1.63      www      5839: =pod
                   5840: 
1.112     bowersj2 5841: =item * &domainlogo()
1.63      www      5842: 
                   5843: Inputs: $domain (usually will be undef)
                   5844: 
                   5845: Returns: A link to a domain logo, if the domain logo exists.
                   5846: If the domain logo does not exist, a description of the domain.
                   5847: 
                   5848: =cut
1.112     bowersj2 5849: 
1.63      www      5850: ###############################################
                   5851: sub domainlogo {
1.517     raeburn  5852:     my $domain = &determinedomain(shift);
1.518     albertel 5853:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5854:     # See if there is a logo
                   5855:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5856:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5857:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5858: 	    if ($imgsrc =~ m{^/res/}) {
                   5859: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5860: 		&Apache::lonnet::repcopy($local_name);
                   5861: 	    }
                   5862: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5863:         } 
                   5864:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5865:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5866:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5867:     } else {
1.60      matthew  5868:         return '';
1.59      www      5869:     }
                   5870: }
1.63      www      5871: ##############################################
                   5872: 
                   5873: =pod
                   5874: 
1.112     bowersj2 5875: =item * &designparm()
1.63      www      5876: 
                   5877: Inputs: $which parameter; $domain (usually will be undef)
                   5878: 
                   5879: Returns: value of designparamter $which
                   5880: 
                   5881: =cut
1.112     bowersj2 5882: 
1.397     albertel 5883: 
1.400     albertel 5884: ##############################################
1.397     albertel 5885: sub designparm {
                   5886:     my ($which,$domain)=@_;
                   5887:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5888:         return $env{'environment.color.'.$which};
1.96      www      5889:     }
1.63      www      5890:     $domain=&determinedomain($domain);
1.1016    raeburn  5891:     my %domdesign;
                   5892:     unless ($domain eq 'public') {
                   5893:         %domdesign = &get_domainconf($domain);
                   5894:     }
1.520     raeburn  5895:     my $output;
1.517     raeburn  5896:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5897:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5898:     } else {
1.520     raeburn  5899:         $output = $defaultdesign{$which};
                   5900:     }
                   5901:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5902:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5903:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5904:             if ($output =~ m{^/res/}) {
                   5905:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5906:                 &Apache::lonnet::repcopy($local_name);
                   5907:             }
1.520     raeburn  5908:             $output = &lonhttpdurl($output);
                   5909:         }
1.63      www      5910:     }
1.520     raeburn  5911:     return $output;
1.63      www      5912: }
1.59      www      5913: 
1.822     bisitz   5914: ##############################################
                   5915: =pod
                   5916: 
1.832     bisitz   5917: =item * &authorspace()
                   5918: 
1.1028    raeburn  5919: Inputs: $url (usually will be undef).
1.832     bisitz   5920: 
1.1132    raeburn  5921: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5922:          directory being viewed (or for which action is being taken). 
                   5923:          If $url is provided, and begins /priv/<domain>/<uname>
                   5924:          the path will be that portion of the $context argument.
                   5925:          Otherwise the path will be for the author space of the current
                   5926:          user when the current role is author, or for that of the 
                   5927:          co-author/assistant co-author space when the current role 
                   5928:          is co-author or assistant co-author.
1.832     bisitz   5929: 
                   5930: =cut
                   5931: 
                   5932: sub authorspace {
1.1028    raeburn  5933:     my ($url) = @_;
                   5934:     if ($url ne '') {
                   5935:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5936:            return $1;
                   5937:         }
                   5938:     }
1.832     bisitz   5939:     my $caname = '';
1.1024    www      5940:     my $cadom = '';
1.1028    raeburn  5941:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5942:         ($cadom,$caname) =
1.832     bisitz   5943:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5944:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5945:         $caname = $env{'user.name'};
1.1024    www      5946:         $cadom = $env{'user.domain'};
1.832     bisitz   5947:     }
1.1028    raeburn  5948:     if (($caname ne '') && ($cadom ne '')) {
                   5949:         return "/priv/$cadom/$caname/";
                   5950:     }
                   5951:     return;
1.832     bisitz   5952: }
                   5953: 
                   5954: ##############################################
                   5955: =pod
                   5956: 
1.822     bisitz   5957: =item * &head_subbox()
                   5958: 
                   5959: Inputs: $content (contains HTML code with page functions, etc.)
                   5960: 
                   5961: Returns: HTML div with $content
                   5962:          To be included in page header
                   5963: 
                   5964: =cut
                   5965: 
                   5966: sub head_subbox {
                   5967:     my ($content)=@_;
                   5968:     my $output =
1.993     raeburn  5969:         '<div class="LC_head_subbox">'
1.822     bisitz   5970:        .$content
                   5971:        .'</div>'
                   5972: }
                   5973: 
                   5974: ##############################################
                   5975: =pod
                   5976: 
                   5977: =item * &CSTR_pageheader()
                   5978: 
1.1026    raeburn  5979: Input: (optional) filename from which breadcrumb trail is built.
                   5980:        In most cases no input as needed, as $env{'request.filename'}
                   5981:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5982: 
                   5983: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5984:          To be included on Authoring Space pages
1.822     bisitz   5985: 
                   5986: =cut
                   5987: 
                   5988: sub CSTR_pageheader {
1.1026    raeburn  5989:     my ($trailfile) = @_;
                   5990:     if ($trailfile eq '') {
                   5991:         $trailfile = $env{'request.filename'};
                   5992:     }
                   5993: 
                   5994: # this is for resources; directories have customtitle, and crumbs
                   5995: # and select recent are created in lonpubdir.pm
                   5996: 
                   5997:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5998:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5999:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6000:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6001:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6002: 
                   6003:     my $parentpath = '';
                   6004:     my $lastitem = '';
                   6005:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6006:         $parentpath = $1;
                   6007:         $lastitem = $2;
                   6008:     } else {
                   6009:         $lastitem = $thisdisfn;
                   6010:     }
1.921     bisitz   6011: 
1.1246    raeburn  6012:     my ($crsauthor,$title);
                   6013:     if (($env{'request.course.id'}) &&
                   6014:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6015:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6016:         $crsauthor = 1;
                   6017:         $title = &mt('Course Authoring Space');
                   6018:     } else {
                   6019:         $title = &mt('Authoring Space');
                   6020:     }
                   6021: 
1.1314    raeburn  6022:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  6023:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6024:         $target = '';
                   6025:         $crumbtarget = '';
1.1313    raeburn  6026:     }
                   6027: 
1.921     bisitz   6028:     my $output =
1.822     bisitz   6029:          '<div>'
                   6030:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6031:         .'<b>'.$title.'</b> '
1.1314    raeburn  6032:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6033:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6034: 
                   6035:     if ($lastitem) {
                   6036:         $output .=
                   6037:              '<span class="LC_filename">'
                   6038:             .$lastitem
                   6039:             .'</span>';
                   6040:     }
1.1245    raeburn  6041: 
1.1246    raeburn  6042:     if ($crsauthor) {
                   6043:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   6044:     } else {
                   6045:         $output .=
                   6046:              '<br />'
1.1314    raeburn  6047:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6048:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6049:             .'</form>'
                   6050:             .&Apache::lonmenu::constspaceform();
                   6051:     }
                   6052:     $output .= '</div>';
1.921     bisitz   6053: 
                   6054:     return $output;
1.822     bisitz   6055: }
                   6056: 
1.60      matthew  6057: ###############################################
                   6058: ###############################################
                   6059: 
                   6060: =pod
                   6061: 
1.112     bowersj2 6062: =back
                   6063: 
1.549     albertel 6064: =head1 HTML Helpers
1.112     bowersj2 6065: 
                   6066: =over 4
                   6067: 
                   6068: =item * &bodytag()
1.60      matthew  6069: 
                   6070: Returns a uniform header for LON-CAPA web pages.
                   6071: 
                   6072: Inputs: 
                   6073: 
1.112     bowersj2 6074: =over 4
                   6075: 
                   6076: =item * $title, A title to be displayed on the page.
                   6077: 
                   6078: =item * $function, the current role (can be undef).
                   6079: 
                   6080: =item * $addentries, extra parameters for the <body> tag.
                   6081: 
                   6082: =item * $bodyonly, if defined, only return the <body> tag.
                   6083: 
                   6084: =item * $domain, if defined, force a given domain.
                   6085: 
                   6086: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6087:             text interface only)
1.60      matthew  6088: 
1.814     bisitz   6089: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6090:                      navigational links
1.317     albertel 6091: 
1.338     albertel 6092: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6093: 
1.460     albertel 6094: =item * $args, optional argument valid values are
                   6095:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6096:             use_absolute     -> for external resource or syllabus, this will
                   6097:                                 contain https://<hostname> if server uses
                   6098:                                 https (as per hosts.tab), but request is for http
                   6099:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6100: 
1.1096    raeburn  6101: =item * $advtoolsref, optional argument, ref to an array containing
                   6102:             inlineremote items to be added in "Functions" menu below
                   6103:             breadcrumbs.
                   6104: 
1.1316    raeburn  6105: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6106:             course, if LON-CAPA is in LTI Provider context. Value is
                   6107:             the scope of use, i.e., launch was for access to a single, a map
                   6108:             or the entire course.
                   6109: 
                   6110: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6111:             context, this will contain the URL for the landing item in
                   6112:             the course, after launch from an LTI Consumer
                   6113: 
1.1318    raeburn  6114: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6115:             context, this will contain a reference to hash of items
                   6116:             to be included in the page header and/or inline menu.
                   6117: 
1.112     bowersj2 6118: =back
                   6119: 
1.60      matthew  6120: Returns: A uniform header for LON-CAPA web pages.  
                   6121: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6122: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6123: other decorations will be returned.
                   6124: 
                   6125: =cut
                   6126: 
1.54      www      6127: sub bodytag {
1.831     bisitz   6128:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6129:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
                   6130:         $ltimenu,$menucoll,$menuref)=@_;
1.339     albertel 6131: 
1.954     raeburn  6132:     my $public;
                   6133:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6134:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6135:         $public = 1;
                   6136:     }
1.460     albertel 6137:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6138:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6139:     my $hostname = $args->{'hostname'};
1.339     albertel 6140: 
1.183     matthew  6141:     $function = &get_users_function() if (!$function);
1.339     albertel 6142:     my $img =    &designparm($function.'.img',$domain);
                   6143:     my $font =   &designparm($function.'.font',$domain);
                   6144:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6145: 
1.803     bisitz   6146:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6147: 		   'bgcolor' => $pgbg,
1.339     albertel 6148: 		   'text'    => $font,
                   6149:                    'alink'   => &designparm($function.'.alink',$domain),
                   6150: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6151: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6152:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6153: 
1.63      www      6154:  # role and realm
1.1178    raeburn  6155:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6156:     if ($realm) {
                   6157:         $realm = '/'.$realm;
                   6158:     }
1.1357    raeburn  6159:     if ($role eq 'ca') {
1.479     albertel 6160:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6161:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6162:     } 
1.55      www      6163: # realm
1.1357    raeburn  6164:     my ($cid,$sec);
1.258     albertel 6165:     if ($env{'request.course.id'}) {
1.1357    raeburn  6166:         $cid = $env{'request.course.id'};
                   6167:         if ($env{'request.course.sec'}) {
                   6168:             $sec = $env{'request.course.sec'};
                   6169:         }
                   6170:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6171:         if (&Apache::lonnet::is_course($1,$2)) {
                   6172:             $cid = $1.'_'.$2;
                   6173:             $sec = $3;
                   6174:         }
                   6175:     }
                   6176:     if ($cid) {
1.378     raeburn  6177:         if ($env{'request.role'} !~ /^cr/) {
                   6178:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6179:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6180:             if ($env{'request.role.desc'}) {
                   6181:                 $role = $env{'request.role.desc'};
                   6182:             } else {
                   6183:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6184:             }
1.1257    raeburn  6185:         } else {
                   6186:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6187:         }
1.1357    raeburn  6188:         if ($sec) {
                   6189:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6190:         }   
1.1357    raeburn  6191: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6192:     } else {
                   6193:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6194:     }
1.433     albertel 6195: 
1.359     albertel 6196:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6197: 
1.438     albertel 6198:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6199: 
1.101     www      6200: # construct main body tag
1.359     albertel 6201:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6202: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6203: 
1.1131    raeburn  6204:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6205: 
1.1130    raeburn  6206:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6207:         return $bodytag;
1.1130    raeburn  6208:     }
1.359     albertel 6209: 
1.954     raeburn  6210:     if ($public) {
1.433     albertel 6211: 	undef($role);
                   6212:     }
1.1318    raeburn  6213: 
1.1359    raeburn  6214:     my $showcrstitle = 1;
1.1357    raeburn  6215:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6216:         if (ref($ltimenu) eq 'HASH') {
                   6217:             unless ($ltimenu->{'role'}) {
                   6218:                 undef($role);
                   6219:             }
                   6220:             unless ($ltimenu->{'coursetitle'}) {
                   6221:                 $realm='&nbsp;';
1.1359    raeburn  6222:                 $showcrstitle = 0;
                   6223:             }
                   6224:         }
                   6225:     } elsif (($cid) && ($menucoll)) {
                   6226:         if (ref($menuref) eq 'HASH') {
                   6227:             unless ($menuref->{'role'}) {
                   6228:                 undef($role);
                   6229:             }
                   6230:             unless ($menuref->{'crs'}) {
                   6231:                 $realm='&nbsp;';
                   6232:                 $showcrstitle = 0;
1.1318    raeburn  6233:             }
                   6234:         }
                   6235:     }
                   6236: 
1.762     bisitz   6237:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6238:     #
                   6239:     # Extra info if you are the DC
                   6240:     my $dc_info = '';
1.1359    raeburn  6241:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6242:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6243:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6244:         $dc_info =~ s/\s+$//;
1.359     albertel 6245:     }
                   6246: 
1.1237    raeburn  6247:     my $crstype;
1.1357    raeburn  6248:     if ($cid) {
                   6249:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6250:     } elsif ($args->{'crstype'}) {
                   6251:         $crstype = $args->{'crstype'};
                   6252:     }
                   6253:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6254:         undef($role);
                   6255:     } else {
1.1242    raeburn  6256:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6257:     }
1.853     droeschl 6258: 
1.903     droeschl 6259:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6260: 
                   6261:         #    if ($env{'request.state'} eq 'construct') {
                   6262:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6263:         #    }
                   6264: 
1.1130    raeburn  6265:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6266:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6267: 
1.1318    raeburn  6268:         unless ($args->{'no_primary_menu'}) {
1.1369  ! raeburn  6269:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
        !          6270:                                                               $args->{'links_disabled'});
1.359     albertel 6271: 
1.1318    raeburn  6272:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6273:                 if ($dc_info) {
                   6274:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6275:                 }
                   6276:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6277:                                <em>$realm</em> $dc_info</div>|;
                   6278:                 return $bodytag;
                   6279:             }
1.894     droeschl 6280: 
1.1318    raeburn  6281:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6282:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6283:             }
1.916     droeschl 6284: 
1.1318    raeburn  6285:             $bodytag .= $right;
1.852     droeschl 6286: 
1.1318    raeburn  6287:             if ($dc_info) {
                   6288:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6289:             }
                   6290:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6291:         }
1.916     droeschl 6292: 
1.1169    raeburn  6293:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6294:         if ($args->{'no_secondary_menu'}) {
                   6295:             return $bodytag;
                   6296:         }
1.1169    raeburn  6297:         #don't show menus for public users
1.954     raeburn  6298:         if (!$public){
1.1318    raeburn  6299:             unless ($args->{'no_inline_menu'}) {
                   6300:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6301:                                                             $args->{'no_primary_menu'},
1.1369  ! raeburn  6302:                                                             $menucoll,$menuref,
        !          6303:                                                             $args->{'links_disabled'});
1.1318    raeburn  6304:             }
1.903     droeschl 6305:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6306:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6307:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6308:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6309:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6310:             } elsif ($forcereg) {
                   6311:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6312:                                                             $args->{'group'},
1.1274    raeburn  6313:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6314:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6315:             } else {
                   6316:                 $bodytag .= 
                   6317:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6318:                                                         $forcereg,$args->{'group'},
                   6319:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6320:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6321:             }
1.903     droeschl 6322:         }else{
                   6323:             # this is to seperate menu from content when there's no secondary
                   6324:             # menu. Especially needed for public accessible ressources.
                   6325:             $bodytag .= '<hr style="clear:both" />';
                   6326:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6327:         }
1.903     droeschl 6328: 
1.235     raeburn  6329:         return $bodytag;
1.182     matthew  6330: }
                   6331: 
1.917     raeburn  6332: sub dc_courseid_toggle {
                   6333:     my ($dc_info) = @_;
1.980     raeburn  6334:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6335:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6336:            &mt('(More ...)').'</a></span>'.
                   6337:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6338: }
                   6339: 
1.330     albertel 6340: sub make_attr_string {
                   6341:     my ($register,$attr_ref) = @_;
                   6342: 
                   6343:     if ($attr_ref && !ref($attr_ref)) {
                   6344: 	die("addentries Must be a hash ref ".
                   6345: 	    join(':',caller(1))." ".
                   6346: 	    join(':',caller(0))." ");
                   6347:     }
                   6348: 
                   6349:     if ($register) {
1.339     albertel 6350: 	my ($on_load,$on_unload);
                   6351: 	foreach my $key (keys(%{$attr_ref})) {
                   6352: 	    if      (lc($key) eq 'onload') {
                   6353: 		$on_load.=$attr_ref->{$key}.';';
                   6354: 		delete($attr_ref->{$key});
                   6355: 
                   6356: 	    } elsif (lc($key) eq 'onunload') {
                   6357: 		$on_unload.=$attr_ref->{$key}.';';
                   6358: 		delete($attr_ref->{$key});
                   6359: 	    }
                   6360: 	}
1.953     droeschl 6361: 	$attr_ref->{'onload'}  = $on_load;
                   6362: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6363:     }
1.339     albertel 6364: 
1.330     albertel 6365:     my $attr_string;
1.1159    raeburn  6366:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6367: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6368:     }
                   6369:     return $attr_string;
                   6370: }
                   6371: 
                   6372: 
1.182     matthew  6373: ###############################################
1.251     albertel 6374: ###############################################
                   6375: 
                   6376: =pod
                   6377: 
                   6378: =item * &endbodytag()
                   6379: 
                   6380: Returns a uniform footer for LON-CAPA web pages.
                   6381: 
1.635     raeburn  6382: Inputs: 1 - optional reference to an args hash
                   6383: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6384: a 'Continue' link is not displayed if the page contains an
                   6385: internal redirect in the <head></head> section,
                   6386: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6387: 
                   6388: =cut
                   6389: 
                   6390: sub endbodytag {
1.635     raeburn  6391:     my ($args) = @_;
1.1080    raeburn  6392:     my $endbodytag;
                   6393:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6394:         $endbodytag='</body>';
                   6395:     }
1.315     albertel 6396:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6397:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6398: 	    $endbodytag=
                   6399: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6400: 	        &mt('Continue').'</a>'.
                   6401: 	        $endbodytag;
                   6402:         }
1.315     albertel 6403:     }
1.251     albertel 6404:     return $endbodytag;
                   6405: }
                   6406: 
1.352     albertel 6407: =pod
                   6408: 
                   6409: =item * &standard_css()
                   6410: 
                   6411: Returns a style sheet
                   6412: 
                   6413: Inputs: (all optional)
                   6414:             domain         -> force to color decorate a page for a specific
                   6415:                                domain
                   6416:             function       -> force usage of a specific rolish color scheme
                   6417:             bgcolor        -> override the default page bgcolor
                   6418: 
                   6419: =cut
                   6420: 
1.343     albertel 6421: sub standard_css {
1.345     albertel 6422:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6423:     $function  = &get_users_function() if (!$function);
                   6424:     my $img    = &designparm($function.'.img',   $domain);
                   6425:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6426:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6427:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6428: #second colour for later usage
1.345     albertel 6429:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6430:     my $pgbg_or_bgcolor =
                   6431: 	         $bgcolor ||
1.352     albertel 6432: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6433:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6434:     my $alink  = &designparm($function.'.alink', $domain);
                   6435:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6436:     my $link   = &designparm($function.'.link',  $domain);
                   6437: 
1.602     albertel 6438:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6439:     my $mono                 = 'monospace';
1.850     bisitz   6440:     my $data_table_head      = $sidebg;
                   6441:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6442:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6443:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6444:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6445:     my $mail_new             = '#FFBB77';
                   6446:     my $mail_new_hover       = '#DD9955';
                   6447:     my $mail_read            = '#BBBB77';
                   6448:     my $mail_read_hover      = '#999944';
                   6449:     my $mail_replied         = '#AAAA88';
                   6450:     my $mail_replied_hover   = '#888855';
                   6451:     my $mail_other           = '#99BBBB';
                   6452:     my $mail_other_hover     = '#669999';
1.391     albertel 6453:     my $table_header         = '#DDDDDD';
1.489     raeburn  6454:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6455:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6456:     my $button_hover         = '#BF2317';
1.392     albertel 6457: 
1.608     albertel 6458:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6459:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6460:                                              : '0 3px 0 4px';
1.448     albertel 6461: 
1.523     albertel 6462: 
1.343     albertel 6463:     return <<END;
1.947     droeschl 6464: 
                   6465: /* needed for iframe to allow 100% height in FF */
                   6466: body, html { 
                   6467:     margin: 0;
                   6468:     padding: 0 0.5%;
                   6469:     height: 99%; /* to avoid scrollbars */
                   6470: }
                   6471: 
1.795     www      6472: body {
1.911     bisitz   6473:   font-family: $sans;
                   6474:   line-height:130%;
                   6475:   font-size:0.83em;
                   6476:   color:$font;
1.795     www      6477: }
                   6478: 
1.959     onken    6479: a:focus,
                   6480: a:focus img {
1.795     www      6481:   color: red;
                   6482: }
1.698     harmsja  6483: 
1.911     bisitz   6484: form, .inline {
                   6485:   display: inline;
1.795     www      6486: }
1.721     harmsja  6487: 
1.795     www      6488: .LC_right {
1.911     bisitz   6489:   text-align:right;
1.795     www      6490: }
                   6491: 
                   6492: .LC_middle {
1.911     bisitz   6493:   vertical-align:middle;
1.795     www      6494: }
1.721     harmsja  6495: 
1.1130    raeburn  6496: .LC_floatleft {
                   6497:   float: left;
                   6498: }
                   6499: 
                   6500: .LC_floatright {
                   6501:   float: right;
                   6502: }
                   6503: 
1.911     bisitz   6504: .LC_400Box {
                   6505:   width:400px;
                   6506: }
1.721     harmsja  6507: 
1.947     droeschl 6508: .LC_iframecontainer {
                   6509:     width: 98%;
                   6510:     margin: 0;
                   6511:     position: fixed;
                   6512:     top: 8.5em;
                   6513:     bottom: 0;
                   6514: }
                   6515: 
                   6516: .LC_iframecontainer iframe{
                   6517:     border: none;
                   6518:     width: 100%;
                   6519:     height: 100%;
                   6520: }
                   6521: 
1.778     bisitz   6522: .LC_filename {
                   6523:   font-family: $mono;
                   6524:   white-space:pre;
1.921     bisitz   6525:   font-size: 120%;
1.778     bisitz   6526: }
                   6527: 
                   6528: .LC_fileicon {
                   6529:   border: none;
                   6530:   height: 1.3em;
                   6531:   vertical-align: text-bottom;
                   6532:   margin-right: 0.3em;
                   6533:   text-decoration:none;
                   6534: }
                   6535: 
1.1008    www      6536: .LC_setting {
                   6537:   text-decoration:underline;
                   6538: }
                   6539: 
1.350     albertel 6540: .LC_error {
                   6541:   color: red;
                   6542: }
1.795     www      6543: 
1.1097    bisitz   6544: .LC_warning {
                   6545:   color: darkorange;
                   6546: }
                   6547: 
1.457     albertel 6548: .LC_diff_removed {
1.733     bisitz   6549:   color: red;
1.394     albertel 6550: }
1.532     albertel 6551: 
                   6552: .LC_info,
1.457     albertel 6553: .LC_success,
                   6554: .LC_diff_added {
1.350     albertel 6555:   color: green;
                   6556: }
1.795     www      6557: 
1.802     bisitz   6558: div.LC_confirm_box {
                   6559:   background-color: #FAFAFA;
                   6560:   border: 1px solid $lg_border_color;
                   6561:   margin-right: 0;
                   6562:   padding: 5px;
                   6563: }
                   6564: 
                   6565: div.LC_confirm_box .LC_error img,
                   6566: div.LC_confirm_box .LC_success img {
                   6567:   vertical-align: middle;
                   6568: }
                   6569: 
1.1242    raeburn  6570: .LC_maxwidth {
                   6571:   max-width: 100%;
                   6572:   height: auto;
                   6573: }
                   6574: 
1.1243    raeburn  6575: .LC_textsize_mobile {
                   6576:   \@media only screen and (max-device-width: 480px) {
                   6577:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6578:   }
                   6579: }
                   6580: 
1.440     albertel 6581: .LC_icon {
1.771     droeschl 6582:   border: none;
1.790     droeschl 6583:   vertical-align: middle;
1.771     droeschl 6584: }
                   6585: 
1.543     albertel 6586: .LC_docs_spacer {
                   6587:   width: 25px;
                   6588:   height: 1px;
1.771     droeschl 6589:   border: none;
1.543     albertel 6590: }
1.346     albertel 6591: 
1.532     albertel 6592: .LC_internal_info {
1.735     bisitz   6593:   color: #999999;
1.532     albertel 6594: }
                   6595: 
1.794     www      6596: .LC_discussion {
1.1050    www      6597:   background: $data_table_dark;
1.911     bisitz   6598:   border: 1px solid black;
                   6599:   margin: 2px;
1.794     www      6600: }
                   6601: 
                   6602: .LC_disc_action_left {
1.1050    www      6603:   background: $sidebg;
1.911     bisitz   6604:   text-align: left;
1.1050    www      6605:   padding: 4px;
                   6606:   margin: 2px;
1.794     www      6607: }
                   6608: 
                   6609: .LC_disc_action_right {
1.1050    www      6610:   background: $sidebg;
1.911     bisitz   6611:   text-align: right;
1.1050    www      6612:   padding: 4px;
                   6613:   margin: 2px;
1.794     www      6614: }
                   6615: 
                   6616: .LC_disc_new_item {
1.911     bisitz   6617:   background: white;
                   6618:   border: 2px solid red;
1.1050    www      6619:   margin: 4px;
                   6620:   padding: 4px;
1.794     www      6621: }
                   6622: 
                   6623: .LC_disc_old_item {
1.911     bisitz   6624:   background: white;
1.1050    www      6625:   margin: 4px;
                   6626:   padding: 4px;
1.794     www      6627: }
                   6628: 
1.458     albertel 6629: table.LC_pastsubmission {
                   6630:   border: 1px solid black;
                   6631:   margin: 2px;
                   6632: }
                   6633: 
1.924     bisitz   6634: table#LC_menubuttons {
1.345     albertel 6635:   width: 100%;
                   6636:   background: $pgbg;
1.392     albertel 6637:   border: 2px;
1.402     albertel 6638:   border-collapse: separate;
1.803     bisitz   6639:   padding: 0;
1.345     albertel 6640: }
1.392     albertel 6641: 
1.801     tempelho 6642: table#LC_title_bar a {
                   6643:   color: $fontmenu;
                   6644: }
1.836     bisitz   6645: 
1.807     droeschl 6646: table#LC_title_bar {
1.819     tempelho 6647:   clear: both;
1.836     bisitz   6648:   display: none;
1.807     droeschl 6649: }
                   6650: 
1.795     www      6651: table#LC_title_bar,
1.933     droeschl 6652: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6653: table#LC_title_bar.LC_with_remote {
1.359     albertel 6654:   width: 100%;
1.392     albertel 6655:   border-color: $pgbg;
                   6656:   border-style: solid;
                   6657:   border-width: $border;
1.379     albertel 6658:   background: $pgbg;
1.801     tempelho 6659:   color: $fontmenu;
1.392     albertel 6660:   border-collapse: collapse;
1.803     bisitz   6661:   padding: 0;
1.819     tempelho 6662:   margin: 0;
1.359     albertel 6663: }
1.795     www      6664: 
1.933     droeschl 6665: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6666:     margin: 0;
                   6667:     padding: 0;
1.933     droeschl 6668:     position: relative;
                   6669:     list-style: none;
1.913     droeschl 6670: }
1.933     droeschl 6671: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6672:     display: inline;
                   6673: }
1.933     droeschl 6674: 
                   6675: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6676:     padding: 0;
1.933     droeschl 6677:     margin: 0;
                   6678:     float: left;
1.913     droeschl 6679: }
1.933     droeschl 6680: .LC_breadcrumb_tools_tools {
                   6681:     padding: 0;
                   6682:     margin: 0;
1.913     droeschl 6683:     float: right;
                   6684: }
                   6685: 
1.1240    raeburn  6686: .LC_placement_prog {
                   6687:     padding-right: 20px;
                   6688:     font-weight: bold;
                   6689:     font-size: 90%;
                   6690: }
                   6691: 
1.359     albertel 6692: table#LC_title_bar td {
                   6693:   background: $tabbg;
                   6694: }
1.795     www      6695: 
1.911     bisitz   6696: table#LC_menubuttons img {
1.803     bisitz   6697:   border: none;
1.346     albertel 6698: }
1.795     www      6699: 
1.842     droeschl 6700: .LC_breadcrumbs_component {
1.911     bisitz   6701:   float: right;
                   6702:   margin: 0 1em;
1.357     albertel 6703: }
1.842     droeschl 6704: .LC_breadcrumbs_component img {
1.911     bisitz   6705:   vertical-align: middle;
1.777     tempelho 6706: }
1.795     www      6707: 
1.1243    raeburn  6708: .LC_breadcrumbs_hoverable {
                   6709:   background: $sidebg;
                   6710: }
                   6711: 
1.383     albertel 6712: td.LC_table_cell_checkbox {
                   6713:   text-align: center;
                   6714: }
1.795     www      6715: 
                   6716: .LC_fontsize_small {
1.911     bisitz   6717:   font-size: 70%;
1.705     tempelho 6718: }
                   6719: 
1.844     bisitz   6720: #LC_breadcrumbs {
1.911     bisitz   6721:   clear:both;
                   6722:   background: $sidebg;
                   6723:   border-bottom: 1px solid $lg_border_color;
                   6724:   line-height: 2.5em;
1.933     droeschl 6725:   overflow: hidden;
1.911     bisitz   6726:   margin: 0;
                   6727:   padding: 0;
1.995     raeburn  6728:   text-align: left;
1.819     tempelho 6729: }
1.862     bisitz   6730: 
1.1098    bisitz   6731: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6732:   clear:both;
                   6733:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6734:   border: 1px solid $sidebg;
1.1098    bisitz   6735:   margin: 0 0 10px 0;
1.966     bisitz   6736:   padding: 3px;
1.995     raeburn  6737:   text-align: left;
1.822     bisitz   6738: }
                   6739: 
1.795     www      6740: .LC_fontsize_medium {
1.911     bisitz   6741:   font-size: 85%;
1.705     tempelho 6742: }
                   6743: 
1.795     www      6744: .LC_fontsize_large {
1.911     bisitz   6745:   font-size: 120%;
1.705     tempelho 6746: }
                   6747: 
1.346     albertel 6748: .LC_menubuttons_inline_text {
                   6749:   color: $font;
1.698     harmsja  6750:   font-size: 90%;
1.701     harmsja  6751:   padding-left:3px;
1.346     albertel 6752: }
                   6753: 
1.934     droeschl 6754: .LC_menubuttons_inline_text img{
                   6755:   vertical-align: middle;
                   6756: }
                   6757: 
1.1051    www      6758: li.LC_menubuttons_inline_text img {
1.951     onken    6759:   cursor:pointer;
1.1002    droeschl 6760:   text-decoration: none;
1.951     onken    6761: }
                   6762: 
1.526     www      6763: .LC_menubuttons_link {
                   6764:   text-decoration: none;
                   6765: }
1.795     www      6766: 
1.522     albertel 6767: .LC_menubuttons_category {
1.521     www      6768:   color: $font;
1.526     www      6769:   background: $pgbg;
1.521     www      6770:   font-size: larger;
                   6771:   font-weight: bold;
                   6772: }
                   6773: 
1.346     albertel 6774: td.LC_menubuttons_text {
1.911     bisitz   6775:   color: $font;
1.346     albertel 6776: }
1.706     harmsja  6777: 
1.346     albertel 6778: .LC_current_location {
                   6779:   background: $tabbg;
                   6780: }
1.795     www      6781: 
1.1286    raeburn  6782: td.LC_zero_height {
                   6783:   line-height: 0; 
                   6784:   cellpadding: 0;
                   6785: }
                   6786: 
1.938     bisitz   6787: table.LC_data_table {
1.347     albertel 6788:   border: 1px solid #000000;
1.402     albertel 6789:   border-collapse: separate;
1.426     albertel 6790:   border-spacing: 1px;
1.610     albertel 6791:   background: $pgbg;
1.347     albertel 6792: }
1.795     www      6793: 
1.422     albertel 6794: .LC_data_table_dense {
                   6795:   font-size: small;
                   6796: }
1.795     www      6797: 
1.507     raeburn  6798: table.LC_nested_outer {
                   6799:   border: 1px solid #000000;
1.589     raeburn  6800:   border-collapse: collapse;
1.803     bisitz   6801:   border-spacing: 0;
1.507     raeburn  6802:   width: 100%;
                   6803: }
1.795     www      6804: 
1.879     raeburn  6805: table.LC_innerpickbox,
1.507     raeburn  6806: table.LC_nested {
1.803     bisitz   6807:   border: none;
1.589     raeburn  6808:   border-collapse: collapse;
1.803     bisitz   6809:   border-spacing: 0;
1.507     raeburn  6810:   width: 100%;
                   6811: }
1.795     www      6812: 
1.911     bisitz   6813: table.LC_data_table tr th,
                   6814: table.LC_calendar tr th,
1.879     raeburn  6815: table.LC_prior_tries tr th,
                   6816: table.LC_innerpickbox tr th {
1.349     albertel 6817:   font-weight: bold;
                   6818:   background-color: $data_table_head;
1.801     tempelho 6819:   color:$fontmenu;
1.701     harmsja  6820:   font-size:90%;
1.347     albertel 6821: }
1.795     www      6822: 
1.879     raeburn  6823: table.LC_innerpickbox tr th,
                   6824: table.LC_innerpickbox tr td {
                   6825:   vertical-align: top;
                   6826: }
                   6827: 
1.711     raeburn  6828: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6829:   background-color: #CCCCCC;
1.711     raeburn  6830:   font-weight: bold;
                   6831:   text-align: left;
                   6832: }
1.795     www      6833: 
1.912     bisitz   6834: table.LC_data_table tr.LC_odd_row > td {
                   6835:   background-color: $data_table_light;
                   6836:   padding: 2px;
                   6837:   vertical-align: top;
                   6838: }
                   6839: 
1.809     bisitz   6840: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6841:   background-color: $data_table_light;
1.912     bisitz   6842:   vertical-align: top;
                   6843: }
                   6844: 
                   6845: table.LC_data_table tr.LC_even_row > td {
                   6846:   background-color: $data_table_dark;
1.425     albertel 6847:   padding: 2px;
1.900     bisitz   6848:   vertical-align: top;
1.347     albertel 6849: }
1.795     www      6850: 
1.809     bisitz   6851: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6852:   background-color: $data_table_dark;
1.900     bisitz   6853:   vertical-align: top;
1.347     albertel 6854: }
1.795     www      6855: 
1.425     albertel 6856: table.LC_data_table tr.LC_data_table_highlight td {
                   6857:   background-color: $data_table_darker;
                   6858: }
1.795     www      6859: 
1.639     raeburn  6860: table.LC_data_table tr td.LC_leftcol_header {
                   6861:   background-color: $data_table_head;
                   6862:   font-weight: bold;
                   6863: }
1.795     www      6864: 
1.451     albertel 6865: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6866: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6867:   font-weight: bold;
                   6868:   font-style: italic;
                   6869:   text-align: center;
                   6870:   padding: 8px;
1.347     albertel 6871: }
1.795     www      6872: 
1.1114    raeburn  6873: table.LC_data_table tr.LC_empty_row td,
                   6874: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6875:   background-color: $sidebg;
                   6876: }
                   6877: 
                   6878: table.LC_nested tr.LC_empty_row td {
                   6879:   background-color: #FFFFFF;
                   6880: }
                   6881: 
1.890     droeschl 6882: table.LC_caption {
                   6883: }
                   6884: 
1.507     raeburn  6885: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6886:   padding: 4ex
                   6887: }
1.795     www      6888: 
1.507     raeburn  6889: table.LC_nested_outer tr th {
                   6890:   font-weight: bold;
1.801     tempelho 6891:   color:$fontmenu;
1.507     raeburn  6892:   background-color: $data_table_head;
1.701     harmsja  6893:   font-size: small;
1.507     raeburn  6894:   border-bottom: 1px solid #000000;
                   6895: }
1.795     www      6896: 
1.507     raeburn  6897: table.LC_nested_outer tr td.LC_subheader {
                   6898:   background-color: $data_table_head;
                   6899:   font-weight: bold;
                   6900:   font-size: small;
                   6901:   border-bottom: 1px solid #000000;
                   6902:   text-align: right;
1.451     albertel 6903: }
1.795     www      6904: 
1.507     raeburn  6905: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6906:   background-color: #CCCCCC;
1.451     albertel 6907:   font-weight: bold;
                   6908:   font-size: small;
1.507     raeburn  6909:   text-align: center;
                   6910: }
1.795     www      6911: 
1.589     raeburn  6912: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6913: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6914:   text-align: left;
1.451     albertel 6915: }
1.795     www      6916: 
1.507     raeburn  6917: table.LC_nested td {
1.735     bisitz   6918:   background-color: #FFFFFF;
1.451     albertel 6919:   font-size: small;
1.507     raeburn  6920: }
1.795     www      6921: 
1.507     raeburn  6922: table.LC_nested_outer tr th.LC_right_item,
                   6923: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6924: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6925: table.LC_nested tr td.LC_right_item {
1.451     albertel 6926:   text-align: right;
                   6927: }
                   6928: 
1.507     raeburn  6929: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6930:   background-color: #EEEEEE;
1.451     albertel 6931: }
                   6932: 
1.473     raeburn  6933: table.LC_createuser {
                   6934: }
                   6935: 
                   6936: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6937:   font-size: small;
1.473     raeburn  6938: }
                   6939: 
                   6940: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6941:   background-color: #CCCCCC;
1.473     raeburn  6942:   font-weight: bold;
                   6943:   text-align: center;
                   6944: }
                   6945: 
1.349     albertel 6946: table.LC_calendar {
                   6947:   border: 1px solid #000000;
                   6948:   border-collapse: collapse;
1.917     raeburn  6949:   width: 98%;
1.349     albertel 6950: }
1.795     www      6951: 
1.349     albertel 6952: table.LC_calendar_pickdate {
                   6953:   font-size: xx-small;
                   6954: }
1.795     www      6955: 
1.349     albertel 6956: table.LC_calendar tr td {
                   6957:   border: 1px solid #000000;
                   6958:   vertical-align: top;
1.917     raeburn  6959:   width: 14%;
1.349     albertel 6960: }
1.795     www      6961: 
1.349     albertel 6962: table.LC_calendar tr td.LC_calendar_day_empty {
                   6963:   background-color: $data_table_dark;
                   6964: }
1.795     www      6965: 
1.779     bisitz   6966: table.LC_calendar tr td.LC_calendar_day_current {
                   6967:   background-color: $data_table_highlight;
1.777     tempelho 6968: }
1.795     www      6969: 
1.938     bisitz   6970: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6971:   background-color: $mail_new;
                   6972: }
1.795     www      6973: 
1.938     bisitz   6974: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6975:   background-color: $mail_new_hover;
                   6976: }
1.795     www      6977: 
1.938     bisitz   6978: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6979:   background-color: $mail_read;
                   6980: }
1.795     www      6981: 
1.938     bisitz   6982: /*
                   6983: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6984:   background-color: $mail_read_hover;
                   6985: }
1.938     bisitz   6986: */
1.795     www      6987: 
1.938     bisitz   6988: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6989:   background-color: $mail_replied;
                   6990: }
1.795     www      6991: 
1.938     bisitz   6992: /*
                   6993: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6994:   background-color: $mail_replied_hover;
                   6995: }
1.938     bisitz   6996: */
1.795     www      6997: 
1.938     bisitz   6998: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6999:   background-color: $mail_other;
                   7000: }
1.795     www      7001: 
1.938     bisitz   7002: /*
                   7003: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7004:   background-color: $mail_other_hover;
                   7005: }
1.938     bisitz   7006: */
1.494     raeburn  7007: 
1.777     tempelho 7008: table.LC_data_table tr > td.LC_browser_file,
                   7009: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7010:   background: #AAEE77;
1.389     albertel 7011: }
1.795     www      7012: 
1.777     tempelho 7013: table.LC_data_table tr > td.LC_browser_file_locked,
                   7014: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7015:   background: #FFAA99;
1.387     albertel 7016: }
1.795     www      7017: 
1.777     tempelho 7018: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7019:   background: #888888;
1.779     bisitz   7020: }
1.795     www      7021: 
1.777     tempelho 7022: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7023: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7024:   background: #F8F866;
1.777     tempelho 7025: }
1.795     www      7026: 
1.696     bisitz   7027: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7028:   background: #E0E8FF;
1.387     albertel 7029: }
1.696     bisitz   7030: 
1.707     bisitz   7031: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7032:   /* background: #77FF77; */
1.707     bisitz   7033: }
1.795     www      7034: 
1.707     bisitz   7035: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7036:   border-right: 8px solid #FFFF77;
1.707     bisitz   7037: }
1.795     www      7038: 
1.707     bisitz   7039: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7040:   border-right: 8px solid #FFAA77;
1.707     bisitz   7041: }
1.795     www      7042: 
1.707     bisitz   7043: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7044:   border-right: 8px solid #FF7777;
1.707     bisitz   7045: }
1.795     www      7046: 
1.707     bisitz   7047: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7048:   border-right: 8px solid #AAFF77;
1.707     bisitz   7049: }
1.795     www      7050: 
1.707     bisitz   7051: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7052:   border-right: 8px solid #11CC55;
1.707     bisitz   7053: }
                   7054: 
1.388     albertel 7055: span.LC_current_location {
1.701     harmsja  7056:   font-size:larger;
1.388     albertel 7057:   background: $pgbg;
                   7058: }
1.387     albertel 7059: 
1.1029    www      7060: span.LC_current_nav_location {
                   7061:   font-weight:bold;
                   7062:   background: $sidebg;
                   7063: }
                   7064: 
1.395     albertel 7065: span.LC_parm_menu_item {
                   7066:   font-size: larger;
                   7067: }
1.795     www      7068: 
1.395     albertel 7069: span.LC_parm_scope_all {
                   7070:   color: red;
                   7071: }
1.795     www      7072: 
1.395     albertel 7073: span.LC_parm_scope_folder {
                   7074:   color: green;
                   7075: }
1.795     www      7076: 
1.395     albertel 7077: span.LC_parm_scope_resource {
                   7078:   color: orange;
                   7079: }
1.795     www      7080: 
1.395     albertel 7081: span.LC_parm_part {
                   7082:   color: blue;
                   7083: }
1.795     www      7084: 
1.911     bisitz   7085: span.LC_parm_folder,
                   7086: span.LC_parm_symb {
1.395     albertel 7087:   font-size: x-small;
                   7088:   font-family: $mono;
                   7089:   color: #AAAAAA;
                   7090: }
                   7091: 
1.977     bisitz   7092: ul.LC_parm_parmlist li {
                   7093:   display: inline-block;
                   7094:   padding: 0.3em 0.8em;
                   7095:   vertical-align: top;
                   7096:   width: 150px;
                   7097:   border-top:1px solid $lg_border_color;
                   7098: }
                   7099: 
1.795     www      7100: td.LC_parm_overview_level_menu,
                   7101: td.LC_parm_overview_map_menu,
                   7102: td.LC_parm_overview_parm_selectors,
                   7103: td.LC_parm_overview_restrictions  {
1.396     albertel 7104:   border: 1px solid black;
                   7105:   border-collapse: collapse;
                   7106: }
1.795     www      7107: 
1.1285    raeburn  7108: span.LC_parm_recursive,
                   7109: td.LC_parm_recursive {
                   7110:   font-weight: bold;
                   7111:   font-size: smaller;
                   7112: }
                   7113: 
1.396     albertel 7114: table.LC_parm_overview_restrictions td {
                   7115:   border-width: 1px 4px 1px 4px;
                   7116:   border-style: solid;
                   7117:   border-color: $pgbg;
                   7118:   text-align: center;
                   7119: }
1.795     www      7120: 
1.396     albertel 7121: table.LC_parm_overview_restrictions th {
                   7122:   background: $tabbg;
                   7123:   border-width: 1px 4px 1px 4px;
                   7124:   border-style: solid;
                   7125:   border-color: $pgbg;
                   7126: }
1.795     www      7127: 
1.398     albertel 7128: table#LC_helpmenu {
1.803     bisitz   7129:   border: none;
1.398     albertel 7130:   height: 55px;
1.803     bisitz   7131:   border-spacing: 0;
1.398     albertel 7132: }
                   7133: 
                   7134: table#LC_helpmenu fieldset legend {
                   7135:   font-size: larger;
                   7136: }
1.795     www      7137: 
1.397     albertel 7138: table#LC_helpmenu_links {
                   7139:   width: 100%;
                   7140:   border: 1px solid black;
                   7141:   background: $pgbg;
1.803     bisitz   7142:   padding: 0;
1.397     albertel 7143:   border-spacing: 1px;
                   7144: }
1.795     www      7145: 
1.397     albertel 7146: table#LC_helpmenu_links tr td {
                   7147:   padding: 1px;
                   7148:   background: $tabbg;
1.399     albertel 7149:   text-align: center;
                   7150:   font-weight: bold;
1.397     albertel 7151: }
1.396     albertel 7152: 
1.795     www      7153: table#LC_helpmenu_links a:link,
                   7154: table#LC_helpmenu_links a:visited,
1.397     albertel 7155: table#LC_helpmenu_links a:active {
                   7156:   text-decoration: none;
                   7157:   color: $font;
                   7158: }
1.795     www      7159: 
1.397     albertel 7160: table#LC_helpmenu_links a:hover {
                   7161:   text-decoration: underline;
                   7162:   color: $vlink;
                   7163: }
1.396     albertel 7164: 
1.417     albertel 7165: .LC_chrt_popup_exists {
                   7166:   border: 1px solid #339933;
                   7167:   margin: -1px;
                   7168: }
1.795     www      7169: 
1.417     albertel 7170: .LC_chrt_popup_up {
                   7171:   border: 1px solid yellow;
                   7172:   margin: -1px;
                   7173: }
1.795     www      7174: 
1.417     albertel 7175: .LC_chrt_popup {
                   7176:   border: 1px solid #8888FF;
                   7177:   background: #CCCCFF;
                   7178: }
1.795     www      7179: 
1.421     albertel 7180: table.LC_pick_box {
                   7181:   border-collapse: separate;
                   7182:   background: white;
                   7183:   border: 1px solid black;
                   7184:   border-spacing: 1px;
                   7185: }
1.795     www      7186: 
1.421     albertel 7187: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7188:   background: $sidebg;
1.421     albertel 7189:   font-weight: bold;
1.900     bisitz   7190:   text-align: left;
1.740     bisitz   7191:   vertical-align: top;
1.421     albertel 7192:   width: 184px;
                   7193:   padding: 8px;
                   7194: }
1.795     www      7195: 
1.579     raeburn  7196: table.LC_pick_box td.LC_pick_box_value {
                   7197:   text-align: left;
                   7198:   padding: 8px;
                   7199: }
1.795     www      7200: 
1.579     raeburn  7201: table.LC_pick_box td.LC_pick_box_select {
                   7202:   text-align: left;
                   7203:   padding: 8px;
                   7204: }
1.795     www      7205: 
1.424     albertel 7206: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7207:   padding: 0;
1.421     albertel 7208:   height: 1px;
                   7209:   background: black;
                   7210: }
1.795     www      7211: 
1.421     albertel 7212: table.LC_pick_box td.LC_pick_box_submit {
                   7213:   text-align: right;
                   7214: }
1.795     www      7215: 
1.579     raeburn  7216: table.LC_pick_box td.LC_evenrow_value {
                   7217:   text-align: left;
                   7218:   padding: 8px;
                   7219:   background-color: $data_table_light;
                   7220: }
1.795     www      7221: 
1.579     raeburn  7222: table.LC_pick_box td.LC_oddrow_value {
                   7223:   text-align: left;
                   7224:   padding: 8px;
                   7225:   background-color: $data_table_light;
                   7226: }
1.795     www      7227: 
1.579     raeburn  7228: span.LC_helpform_receipt_cat {
                   7229:   font-weight: bold;
                   7230: }
1.795     www      7231: 
1.424     albertel 7232: table.LC_group_priv_box {
                   7233:   background: white;
                   7234:   border: 1px solid black;
                   7235:   border-spacing: 1px;
                   7236: }
1.795     www      7237: 
1.424     albertel 7238: table.LC_group_priv_box td.LC_pick_box_title {
                   7239:   background: $tabbg;
                   7240:   font-weight: bold;
                   7241:   text-align: right;
                   7242:   width: 184px;
                   7243: }
1.795     www      7244: 
1.424     albertel 7245: table.LC_group_priv_box td.LC_groups_fixed {
                   7246:   background: $data_table_light;
                   7247:   text-align: center;
                   7248: }
1.795     www      7249: 
1.424     albertel 7250: table.LC_group_priv_box td.LC_groups_optional {
                   7251:   background: $data_table_dark;
                   7252:   text-align: center;
                   7253: }
1.795     www      7254: 
1.424     albertel 7255: table.LC_group_priv_box td.LC_groups_functionality {
                   7256:   background: $data_table_darker;
                   7257:   text-align: center;
                   7258:   font-weight: bold;
                   7259: }
1.795     www      7260: 
1.424     albertel 7261: table.LC_group_priv td {
                   7262:   text-align: left;
1.803     bisitz   7263:   padding: 0;
1.424     albertel 7264: }
                   7265: 
                   7266: .LC_navbuttons {
                   7267:   margin: 2ex 0ex 2ex 0ex;
                   7268: }
1.795     www      7269: 
1.423     albertel 7270: .LC_topic_bar {
                   7271:   font-weight: bold;
                   7272:   background: $tabbg;
1.918     wenzelju 7273:   margin: 1em 0em 1em 2em;
1.805     bisitz   7274:   padding: 3px;
1.918     wenzelju 7275:   font-size: 1.2em;
1.423     albertel 7276: }
1.795     www      7277: 
1.423     albertel 7278: .LC_topic_bar span {
1.918     wenzelju 7279:   left: 0.5em;
                   7280:   position: absolute;
1.423     albertel 7281:   vertical-align: middle;
1.918     wenzelju 7282:   font-size: 1.2em;
1.423     albertel 7283: }
1.795     www      7284: 
1.423     albertel 7285: table.LC_course_group_status {
                   7286:   margin: 20px;
                   7287: }
1.795     www      7288: 
1.423     albertel 7289: table.LC_status_selector td {
                   7290:   vertical-align: top;
                   7291:   text-align: center;
1.424     albertel 7292:   padding: 4px;
                   7293: }
1.795     www      7294: 
1.599     albertel 7295: div.LC_feedback_link {
1.616     albertel 7296:   clear: both;
1.829     kalberla 7297:   background: $sidebg;
1.779     bisitz   7298:   width: 100%;
1.829     kalberla 7299:   padding-bottom: 10px;
                   7300:   border: 1px $tabbg solid;
1.833     kalberla 7301:   height: 22px;
                   7302:   line-height: 22px;
                   7303:   padding-top: 5px;
                   7304: }
                   7305: 
                   7306: div.LC_feedback_link img {
                   7307:   height: 22px;
1.867     kalberla 7308:   vertical-align:middle;
1.829     kalberla 7309: }
                   7310: 
1.911     bisitz   7311: div.LC_feedback_link a {
1.829     kalberla 7312:   text-decoration: none;
1.489     raeburn  7313: }
1.795     www      7314: 
1.867     kalberla 7315: div.LC_comblock {
1.911     bisitz   7316:   display:inline;
1.867     kalberla 7317:   color:$font;
                   7318:   font-size:90%;
                   7319: }
                   7320: 
                   7321: div.LC_feedback_link div.LC_comblock {
                   7322:   padding-left:5px;
                   7323: }
                   7324: 
                   7325: div.LC_feedback_link div.LC_comblock a {
                   7326:   color:$font;
                   7327: }
                   7328: 
1.489     raeburn  7329: span.LC_feedback_link {
1.858     bisitz   7330:   /* background: $feedback_link_bg; */
1.599     albertel 7331:   font-size: larger;
                   7332: }
1.795     www      7333: 
1.599     albertel 7334: span.LC_message_link {
1.858     bisitz   7335:   /* background: $feedback_link_bg; */
1.599     albertel 7336:   font-size: larger;
                   7337:   position: absolute;
                   7338:   right: 1em;
1.489     raeburn  7339: }
1.421     albertel 7340: 
1.515     albertel 7341: table.LC_prior_tries {
1.524     albertel 7342:   border: 1px solid #000000;
                   7343:   border-collapse: separate;
                   7344:   border-spacing: 1px;
1.515     albertel 7345: }
1.523     albertel 7346: 
1.515     albertel 7347: table.LC_prior_tries td {
1.524     albertel 7348:   padding: 2px;
1.515     albertel 7349: }
1.523     albertel 7350: 
                   7351: .LC_answer_correct {
1.795     www      7352:   background: lightgreen;
                   7353:   color: darkgreen;
                   7354:   padding: 6px;
1.523     albertel 7355: }
1.795     www      7356: 
1.523     albertel 7357: .LC_answer_charged_try {
1.797     www      7358:   background: #FFAAAA;
1.795     www      7359:   color: darkred;
                   7360:   padding: 6px;
1.523     albertel 7361: }
1.795     www      7362: 
1.779     bisitz   7363: .LC_answer_not_charged_try,
1.523     albertel 7364: .LC_answer_no_grade,
                   7365: .LC_answer_late {
1.795     www      7366:   background: lightyellow;
1.523     albertel 7367:   color: black;
1.795     www      7368:   padding: 6px;
1.523     albertel 7369: }
1.795     www      7370: 
1.523     albertel 7371: .LC_answer_previous {
1.795     www      7372:   background: lightblue;
                   7373:   color: darkblue;
                   7374:   padding: 6px;
1.523     albertel 7375: }
1.795     www      7376: 
1.779     bisitz   7377: .LC_answer_no_message {
1.777     tempelho 7378:   background: #FFFFFF;
                   7379:   color: black;
1.795     www      7380:   padding: 6px;
1.779     bisitz   7381: }
1.795     www      7382: 
1.1334    raeburn  7383: .LC_answer_unknown,
                   7384: .LC_answer_warning {
1.779     bisitz   7385:   background: orange;
                   7386:   color: black;
1.795     www      7387:   padding: 6px;
1.777     tempelho 7388: }
1.795     www      7389: 
1.529     albertel 7390: span.LC_prior_numerical,
                   7391: span.LC_prior_string,
                   7392: span.LC_prior_custom,
                   7393: span.LC_prior_reaction,
                   7394: span.LC_prior_math {
1.925     bisitz   7395:   font-family: $mono;
1.523     albertel 7396:   white-space: pre;
                   7397: }
                   7398: 
1.525     albertel 7399: span.LC_prior_string {
1.925     bisitz   7400:   font-family: $mono;
1.525     albertel 7401:   white-space: pre;
                   7402: }
                   7403: 
1.523     albertel 7404: table.LC_prior_option {
                   7405:   width: 100%;
                   7406:   border-collapse: collapse;
                   7407: }
1.795     www      7408: 
1.911     bisitz   7409: table.LC_prior_rank,
1.795     www      7410: table.LC_prior_match {
1.528     albertel 7411:   border-collapse: collapse;
                   7412: }
1.795     www      7413: 
1.528     albertel 7414: table.LC_prior_option tr td,
                   7415: table.LC_prior_rank tr td,
                   7416: table.LC_prior_match tr td {
1.524     albertel 7417:   border: 1px solid #000000;
1.515     albertel 7418: }
                   7419: 
1.855     bisitz   7420: .LC_nobreak {
1.544     albertel 7421:   white-space: nowrap;
1.519     raeburn  7422: }
                   7423: 
1.576     raeburn  7424: span.LC_cusr_emph {
                   7425:   font-style: italic;
                   7426: }
                   7427: 
1.633     raeburn  7428: span.LC_cusr_subheading {
                   7429:   font-weight: normal;
                   7430:   font-size: 85%;
                   7431: }
                   7432: 
1.861     bisitz   7433: div.LC_docs_entry_move {
1.859     bisitz   7434:   border: 1px solid #BBBBBB;
1.545     albertel 7435:   background: #DDDDDD;
1.861     bisitz   7436:   width: 22px;
1.859     bisitz   7437:   padding: 1px;
                   7438:   margin: 0;
1.545     albertel 7439: }
                   7440: 
1.861     bisitz   7441: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7442: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7443:   font-size: x-small;
                   7444: }
1.795     www      7445: 
1.861     bisitz   7446: .LC_docs_entry_parameter {
                   7447:   white-space: nowrap;
                   7448: }
                   7449: 
1.544     albertel 7450: .LC_docs_copy {
1.545     albertel 7451:   color: #000099;
1.544     albertel 7452: }
1.795     www      7453: 
1.544     albertel 7454: .LC_docs_cut {
1.545     albertel 7455:   color: #550044;
1.544     albertel 7456: }
1.795     www      7457: 
1.544     albertel 7458: .LC_docs_rename {
1.545     albertel 7459:   color: #009900;
1.544     albertel 7460: }
1.795     www      7461: 
1.544     albertel 7462: .LC_docs_remove {
1.545     albertel 7463:   color: #990000;
                   7464: }
                   7465: 
1.1284    raeburn  7466: .LC_docs_alias {
                   7467:   color: #440055;  
                   7468: }
                   7469: 
1.1286    raeburn  7470: .LC_domprefs_email,
1.1284    raeburn  7471: .LC_docs_alias_name,
1.547     albertel 7472: .LC_docs_reinit_warn,
                   7473: .LC_docs_ext_edit {
                   7474:   font-size: x-small;
                   7475: }
                   7476: 
1.545     albertel 7477: table.LC_docs_adddocs td,
                   7478: table.LC_docs_adddocs th {
                   7479:   border: 1px solid #BBBBBB;
                   7480:   padding: 4px;
                   7481:   background: #DDDDDD;
1.543     albertel 7482: }
                   7483: 
1.584     albertel 7484: table.LC_sty_begin {
                   7485:   background: #BBFFBB;
                   7486: }
1.795     www      7487: 
1.584     albertel 7488: table.LC_sty_end {
                   7489:   background: #FFBBBB;
                   7490: }
                   7491: 
1.589     raeburn  7492: table.LC_double_column {
1.803     bisitz   7493:   border-width: 0;
1.589     raeburn  7494:   border-collapse: collapse;
                   7495:   width: 100%;
                   7496:   padding: 2px;
                   7497: }
                   7498: 
                   7499: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7500:   top: 2px;
1.589     raeburn  7501:   left: 2px;
                   7502:   width: 47%;
                   7503:   vertical-align: top;
                   7504: }
                   7505: 
                   7506: table.LC_double_column tr td.LC_right_col {
                   7507:   top: 2px;
1.779     bisitz   7508:   right: 2px;
1.589     raeburn  7509:   width: 47%;
                   7510:   vertical-align: top;
                   7511: }
                   7512: 
1.591     raeburn  7513: div.LC_left_float {
                   7514:   float: left;
                   7515:   padding-right: 5%;
1.597     albertel 7516:   padding-bottom: 4px;
1.591     raeburn  7517: }
                   7518: 
                   7519: div.LC_clear_float_header {
1.597     albertel 7520:   padding-bottom: 2px;
1.591     raeburn  7521: }
                   7522: 
                   7523: div.LC_clear_float_footer {
1.597     albertel 7524:   padding-top: 10px;
1.591     raeburn  7525:   clear: both;
                   7526: }
                   7527: 
1.597     albertel 7528: div.LC_grade_show_user {
1.941     bisitz   7529: /*  border-left: 5px solid $sidebg; */
                   7530:   border-top: 5px solid #000000;
                   7531:   margin: 50px 0 0 0;
1.936     bisitz   7532:   padding: 15px 0 5px 10px;
1.597     albertel 7533: }
1.795     www      7534: 
1.936     bisitz   7535: div.LC_grade_show_user_odd_row {
1.941     bisitz   7536: /*  border-left: 5px solid #000000; */
                   7537: }
                   7538: 
                   7539: div.LC_grade_show_user div.LC_Box {
                   7540:   margin-right: 50px;
1.597     albertel 7541: }
                   7542: 
                   7543: div.LC_grade_submissions,
                   7544: div.LC_grade_message_center,
1.936     bisitz   7545: div.LC_grade_info_links {
1.597     albertel 7546:   margin: 5px;
                   7547:   width: 99%;
                   7548:   background: #FFFFFF;
                   7549: }
1.795     www      7550: 
1.597     albertel 7551: div.LC_grade_submissions_header,
1.936     bisitz   7552: div.LC_grade_message_center_header {
1.705     tempelho 7553:   font-weight: bold;
                   7554:   font-size: large;
1.597     albertel 7555: }
1.795     www      7556: 
1.597     albertel 7557: div.LC_grade_submissions_body,
1.936     bisitz   7558: div.LC_grade_message_center_body {
1.597     albertel 7559:   border: 1px solid black;
                   7560:   width: 99%;
                   7561:   background: #FFFFFF;
                   7562: }
1.795     www      7563: 
1.613     albertel 7564: table.LC_scantron_action {
                   7565:   width: 100%;
                   7566: }
1.795     www      7567: 
1.613     albertel 7568: table.LC_scantron_action tr th {
1.698     harmsja  7569:   font-weight:bold;
                   7570:   font-style:normal;
1.613     albertel 7571: }
1.795     www      7572: 
1.779     bisitz   7573: .LC_edit_problem_header,
1.614     albertel 7574: div.LC_edit_problem_footer {
1.705     tempelho 7575:   font-weight: normal;
                   7576:   font-size:  medium;
1.602     albertel 7577:   margin: 2px;
1.1060    bisitz   7578:   background-color: $sidebg;
1.600     albertel 7579: }
1.795     www      7580: 
1.600     albertel 7581: div.LC_edit_problem_header,
1.602     albertel 7582: div.LC_edit_problem_header div,
1.614     albertel 7583: div.LC_edit_problem_footer,
                   7584: div.LC_edit_problem_footer div,
1.602     albertel 7585: div.LC_edit_problem_editxml_header,
                   7586: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7587:   z-index: 100;
1.600     albertel 7588: }
1.795     www      7589: 
1.600     albertel 7590: div.LC_edit_problem_header_title {
1.705     tempelho 7591:   font-weight: bold;
                   7592:   font-size: larger;
1.602     albertel 7593:   background: $tabbg;
                   7594:   padding: 3px;
1.1060    bisitz   7595:   margin: 0 0 5px 0;
1.602     albertel 7596: }
1.795     www      7597: 
1.602     albertel 7598: table.LC_edit_problem_header_title {
                   7599:   width: 100%;
1.600     albertel 7600:   background: $tabbg;
1.602     albertel 7601: }
                   7602: 
1.1205    golterma 7603: div.LC_edit_actionbar {
                   7604:     background-color: $sidebg;
1.1218    droeschl 7605:     margin: 0;
                   7606:     padding: 0;
                   7607:     line-height: 200%;
1.602     albertel 7608: }
1.795     www      7609: 
1.1218    droeschl 7610: div.LC_edit_actionbar div{
                   7611:     padding: 0;
                   7612:     margin: 0;
                   7613:     display: inline-block;
1.600     albertel 7614: }
1.795     www      7615: 
1.1124    bisitz   7616: .LC_edit_opt {
                   7617:   padding-left: 1em;
                   7618:   white-space: nowrap;
                   7619: }
                   7620: 
1.1152    golterma 7621: .LC_edit_problem_latexhelper{
                   7622:     text-align: right;
                   7623: }
                   7624: 
                   7625: #LC_edit_problem_colorful div{
                   7626:     margin-left: 40px;
                   7627: }
                   7628: 
1.1205    golterma 7629: #LC_edit_problem_codemirror div{
                   7630:     margin-left: 0px;
                   7631: }
                   7632: 
1.911     bisitz   7633: img.stift {
1.803     bisitz   7634:   border-width: 0;
                   7635:   vertical-align: middle;
1.677     riegler  7636: }
1.680     riegler  7637: 
1.923     bisitz   7638: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7639:   vertical-align: top;
1.777     tempelho 7640: }
1.795     www      7641: 
1.716     raeburn  7642: div.LC_createcourse {
1.911     bisitz   7643:   margin: 10px 10px 10px 10px;
1.716     raeburn  7644: }
                   7645: 
1.917     raeburn  7646: .LC_dccid {
1.1130    raeburn  7647:   float: right;
1.917     raeburn  7648:   margin: 0.2em 0 0 0;
                   7649:   padding: 0;
                   7650:   font-size: 90%;
                   7651:   display:none;
                   7652: }
                   7653: 
1.897     wenzelju 7654: ol.LC_primary_menu a:hover,
1.721     harmsja  7655: ol#LC_MenuBreadcrumbs a:hover,
                   7656: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7657: ul#LC_secondary_menu a:hover,
1.721     harmsja  7658: .LC_FormSectionClearButton input:hover
1.795     www      7659: ul.LC_TabContent   li:hover a {
1.952     onken    7660:   color:$button_hover;
1.911     bisitz   7661:   text-decoration:none;
1.693     droeschl 7662: }
                   7663: 
1.779     bisitz   7664: h1 {
1.911     bisitz   7665:   padding: 0;
                   7666:   line-height:130%;
1.693     droeschl 7667: }
1.698     harmsja  7668: 
1.911     bisitz   7669: h2,
                   7670: h3,
                   7671: h4,
                   7672: h5,
                   7673: h6 {
                   7674:   margin: 5px 0 5px 0;
                   7675:   padding: 0;
                   7676:   line-height:130%;
1.693     droeschl 7677: }
1.795     www      7678: 
                   7679: .LC_hcell {
1.911     bisitz   7680:   padding:3px 15px 3px 15px;
                   7681:   margin: 0;
                   7682:   background-color:$tabbg;
                   7683:   color:$fontmenu;
                   7684:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7685: }
1.795     www      7686: 
1.840     bisitz   7687: .LC_Box > .LC_hcell {
1.911     bisitz   7688:   margin: 0 -10px 10px -10px;
1.835     bisitz   7689: }
                   7690: 
1.721     harmsja  7691: .LC_noBorder {
1.911     bisitz   7692:   border: 0;
1.698     harmsja  7693: }
1.693     droeschl 7694: 
1.721     harmsja  7695: .LC_FormSectionClearButton input {
1.911     bisitz   7696:   background-color:transparent;
                   7697:   border: none;
                   7698:   cursor:pointer;
                   7699:   text-decoration:underline;
1.693     droeschl 7700: }
1.763     bisitz   7701: 
                   7702: .LC_help_open_topic {
1.911     bisitz   7703:   color: #FFFFFF;
                   7704:   background-color: #EEEEFF;
                   7705:   margin: 1px;
                   7706:   padding: 4px;
                   7707:   border: 1px solid #000033;
                   7708:   white-space: nowrap;
                   7709:   /* vertical-align: middle; */
1.759     neumanie 7710: }
1.693     droeschl 7711: 
1.911     bisitz   7712: dl,
                   7713: ul,
                   7714: div,
                   7715: fieldset {
                   7716:   margin: 10px 10px 10px 0;
                   7717:   /* overflow: hidden; */
1.693     droeschl 7718: }
1.795     www      7719: 
1.1211    raeburn  7720: article.geogebraweb div {
                   7721:     margin: 0;
                   7722: }
                   7723: 
1.838     bisitz   7724: fieldset > legend {
1.911     bisitz   7725:   font-weight: bold;
                   7726:   padding: 0 5px 0 5px;
1.838     bisitz   7727: }
                   7728: 
1.813     bisitz   7729: #LC_nav_bar {
1.911     bisitz   7730:   float: left;
1.995     raeburn  7731:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7732:   margin: 0 0 2px 0;
1.807     droeschl 7733: }
                   7734: 
1.916     droeschl 7735: #LC_realm {
                   7736:   margin: 0.2em 0 0 0;
                   7737:   padding: 0;
                   7738:   font-weight: bold;
                   7739:   text-align: center;
1.995     raeburn  7740:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7741: }
                   7742: 
1.911     bisitz   7743: #LC_nav_bar em {
                   7744:   font-weight: bold;
                   7745:   font-style: normal;
1.807     droeschl 7746: }
                   7747: 
1.897     wenzelju 7748: ol.LC_primary_menu {
1.934     droeschl 7749:   margin: 0;
1.1076    raeburn  7750:   padding: 0;
1.807     droeschl 7751: }
                   7752: 
1.852     droeschl 7753: ol#LC_PathBreadcrumbs {
1.911     bisitz   7754:   margin: 0;
1.693     droeschl 7755: }
                   7756: 
1.897     wenzelju 7757: ol.LC_primary_menu li {
1.1076    raeburn  7758:   color: RGB(80, 80, 80);
                   7759:   vertical-align: middle;
                   7760:   text-align: left;
                   7761:   list-style: none;
1.1205    golterma 7762:   position: relative;
1.1076    raeburn  7763:   float: left;
1.1205    golterma 7764:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7765:   line-height: 1.5em;
1.1076    raeburn  7766: }
                   7767: 
1.1205    golterma 7768: ol.LC_primary_menu li a,
                   7769: ol.LC_primary_menu li p {
1.1076    raeburn  7770:   display: block;
                   7771:   margin: 0;
                   7772:   padding: 0 5px 0 10px;
                   7773:   text-decoration: none;
                   7774: }
                   7775: 
1.1205    golterma 7776: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7777:   display: inline-block;
                   7778:   width: 95%;
                   7779:   text-align: left;
                   7780: }
                   7781: 
                   7782: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7783:   display: inline-block;	
                   7784:   width: 5%;
                   7785:   float: right;
                   7786:   text-align: right;
                   7787:   font-size: 70%;
                   7788: }
                   7789: 
                   7790: ol.LC_primary_menu ul {
1.1076    raeburn  7791:   display: none;
1.1205    golterma 7792:   width: 15em;
1.1076    raeburn  7793:   background-color: $data_table_light;
1.1205    golterma 7794:   position: absolute;
                   7795:   top: 100%;
1.1076    raeburn  7796: }
                   7797: 
1.1205    golterma 7798: ol.LC_primary_menu ul ul {
                   7799:   left: 100%;
                   7800:   top: 0;
                   7801: }
                   7802: 
                   7803: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7804:   display: block;
                   7805:   position: absolute;
                   7806:   margin: 0;
                   7807:   padding: 0;
1.1078    raeburn  7808:   z-index: 2;
1.1076    raeburn  7809: }
                   7810: 
                   7811: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7812: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7813:   font-size: 90%;
1.911     bisitz   7814:   vertical-align: top;
1.1076    raeburn  7815:   float: none;
1.1079    raeburn  7816:   border-left: 1px solid black;
                   7817:   border-right: 1px solid black;
1.1205    golterma 7818: /* A dark bottom border to visualize different menu options; 
                   7819: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7820:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7821: }
                   7822: 
1.1205    golterma 7823: ol.LC_primary_menu li li p:hover {
                   7824:   color:$button_hover;
                   7825:   text-decoration:none;
                   7826:   background-color:$data_table_dark;
1.1076    raeburn  7827: }
                   7828: 
                   7829: ol.LC_primary_menu li li a:hover {
                   7830:    color:$button_hover;
                   7831:    background-color:$data_table_dark;
1.693     droeschl 7832: }
                   7833: 
1.1205    golterma 7834: /* Font-size equal to the size of the predecessors*/
                   7835: ol.LC_primary_menu li:hover li li {
                   7836:   font-size: 100%;
                   7837: }
                   7838: 
1.897     wenzelju 7839: ol.LC_primary_menu li img {
1.911     bisitz   7840:   vertical-align: bottom;
1.934     droeschl 7841:   height: 1.1em;
1.1077    raeburn  7842:   margin: 0.2em 0 0 0;
1.693     droeschl 7843: }
                   7844: 
1.897     wenzelju 7845: ol.LC_primary_menu a {
1.911     bisitz   7846:   color: RGB(80, 80, 80);
                   7847:   text-decoration: none;
1.693     droeschl 7848: }
1.795     www      7849: 
1.949     droeschl 7850: ol.LC_primary_menu a.LC_new_message {
                   7851:   font-weight:bold;
                   7852:   color: darkred;
                   7853: }
                   7854: 
1.975     raeburn  7855: ol.LC_docs_parameters {
                   7856:   margin-left: 0;
                   7857:   padding: 0;
                   7858:   list-style: none;
                   7859: }
                   7860: 
                   7861: ol.LC_docs_parameters li {
                   7862:   margin: 0;
                   7863:   padding-right: 20px;
                   7864:   display: inline;
                   7865: }
                   7866: 
1.976     raeburn  7867: ol.LC_docs_parameters li:before {
                   7868:   content: "\\002022 \\0020";
                   7869: }
                   7870: 
                   7871: li.LC_docs_parameters_title {
                   7872:   font-weight: bold;
                   7873: }
                   7874: 
                   7875: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7876:   content: "";
                   7877: }
                   7878: 
1.897     wenzelju 7879: ul#LC_secondary_menu {
1.1107    raeburn  7880:   clear: right;
1.911     bisitz   7881:   color: $fontmenu;
                   7882:   background: $tabbg;
                   7883:   list-style: none;
                   7884:   padding: 0;
                   7885:   margin: 0;
                   7886:   width: 100%;
1.995     raeburn  7887:   text-align: left;
1.1107    raeburn  7888:   float: left;
1.808     droeschl 7889: }
                   7890: 
1.897     wenzelju 7891: ul#LC_secondary_menu li {
1.911     bisitz   7892:   font-weight: bold;
                   7893:   line-height: 1.8em;
1.1107    raeburn  7894:   border-right: 1px solid black;
                   7895:   float: left;
                   7896: }
                   7897: 
                   7898: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7899:   background-color: $data_table_light;
                   7900: }
                   7901: 
                   7902: ul#LC_secondary_menu li a {
1.911     bisitz   7903:   padding: 0 0.8em;
1.1107    raeburn  7904: }
                   7905: 
                   7906: ul#LC_secondary_menu li ul {
                   7907:   display: none;
                   7908: }
                   7909: 
                   7910: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7911:   display: block;
                   7912:   position: absolute;
                   7913:   margin: 0;
                   7914:   padding: 0;
                   7915:   list-style:none;
                   7916:   float: none;
                   7917:   background-color: $data_table_light;
                   7918:   z-index: 2;
                   7919:   margin-left: -1px;
                   7920: }
                   7921: 
                   7922: ul#LC_secondary_menu li ul li {
                   7923:   font-size: 90%;
                   7924:   vertical-align: top;
                   7925:   border-left: 1px solid black;
1.911     bisitz   7926:   border-right: 1px solid black;
1.1119    raeburn  7927:   background-color: $data_table_light;
1.1107    raeburn  7928:   list-style:none;
                   7929:   float: none;
                   7930: }
                   7931: 
                   7932: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7933:   background-color: $data_table_dark;
1.807     droeschl 7934: }
                   7935: 
1.847     tempelho 7936: ul.LC_TabContent {
1.911     bisitz   7937:   display:block;
                   7938:   background: $sidebg;
                   7939:   border-bottom: solid 1px $lg_border_color;
                   7940:   list-style:none;
1.1020    raeburn  7941:   margin: -1px -10px 0 -10px;
1.911     bisitz   7942:   padding: 0;
1.693     droeschl 7943: }
                   7944: 
1.795     www      7945: ul.LC_TabContent li,
                   7946: ul.LC_TabContentBigger li {
1.911     bisitz   7947:   float:left;
1.741     harmsja  7948: }
1.795     www      7949: 
1.897     wenzelju 7950: ul#LC_secondary_menu li a {
1.911     bisitz   7951:   color: $fontmenu;
                   7952:   text-decoration: none;
1.693     droeschl 7953: }
1.795     www      7954: 
1.721     harmsja  7955: ul.LC_TabContent {
1.952     onken    7956:   min-height:20px;
1.721     harmsja  7957: }
1.795     www      7958: 
                   7959: ul.LC_TabContent li {
1.911     bisitz   7960:   vertical-align:middle;
1.959     onken    7961:   padding: 0 16px 0 10px;
1.911     bisitz   7962:   background-color:$tabbg;
                   7963:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7964:   border-left: solid 1px $font;
1.721     harmsja  7965: }
1.795     www      7966: 
1.847     tempelho 7967: ul.LC_TabContent .right {
1.911     bisitz   7968:   float:right;
1.847     tempelho 7969: }
                   7970: 
1.911     bisitz   7971: ul.LC_TabContent li a,
                   7972: ul.LC_TabContent li {
                   7973:   color:rgb(47,47,47);
                   7974:   text-decoration:none;
                   7975:   font-size:95%;
                   7976:   font-weight:bold;
1.952     onken    7977:   min-height:20px;
                   7978: }
                   7979: 
1.959     onken    7980: ul.LC_TabContent li a:hover,
                   7981: ul.LC_TabContent li a:focus {
1.952     onken    7982:   color: $button_hover;
1.959     onken    7983:   background:none;
                   7984:   outline:none;
1.952     onken    7985: }
                   7986: 
                   7987: ul.LC_TabContent li:hover {
                   7988:   color: $button_hover;
                   7989:   cursor:pointer;
1.721     harmsja  7990: }
1.795     www      7991: 
1.911     bisitz   7992: ul.LC_TabContent li.active {
1.952     onken    7993:   color: $font;
1.911     bisitz   7994:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7995:   border-bottom:solid 1px #FFFFFF;
                   7996:   cursor: default;
1.744     ehlerst  7997: }
1.795     www      7998: 
1.959     onken    7999: ul.LC_TabContent li.active a {
                   8000:   color:$font;
                   8001:   background:#FFFFFF;
                   8002:   outline: none;
                   8003: }
1.1047    raeburn  8004: 
                   8005: ul.LC_TabContent li.goback {
                   8006:   float: left;
                   8007:   border-left: none;
                   8008: }
                   8009: 
1.870     tempelho 8010: #maincoursedoc {
1.911     bisitz   8011:   clear:both;
1.870     tempelho 8012: }
                   8013: 
                   8014: ul.LC_TabContentBigger {
1.911     bisitz   8015:   display:block;
                   8016:   list-style:none;
                   8017:   padding: 0;
1.870     tempelho 8018: }
                   8019: 
1.795     www      8020: ul.LC_TabContentBigger li {
1.911     bisitz   8021:   vertical-align:bottom;
                   8022:   height: 30px;
                   8023:   font-size:110%;
                   8024:   font-weight:bold;
                   8025:   color: #737373;
1.841     tempelho 8026: }
                   8027: 
1.957     onken    8028: ul.LC_TabContentBigger li.active {
                   8029:   position: relative;
                   8030:   top: 1px;
                   8031: }
                   8032: 
1.870     tempelho 8033: ul.LC_TabContentBigger li a {
1.911     bisitz   8034:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8035:   height: 30px;
                   8036:   line-height: 30px;
                   8037:   text-align: center;
                   8038:   display: block;
                   8039:   text-decoration: none;
1.958     onken    8040:   outline: none;  
1.741     harmsja  8041: }
1.795     www      8042: 
1.870     tempelho 8043: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8044:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8045:   color:$font;
1.744     ehlerst  8046: }
1.795     www      8047: 
1.870     tempelho 8048: ul.LC_TabContentBigger li b {
1.911     bisitz   8049:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8050:   display: block;
                   8051:   float: left;
                   8052:   padding: 0 30px;
1.957     onken    8053:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8054: }
                   8055: 
1.956     onken    8056: ul.LC_TabContentBigger li:hover b {
                   8057:   color:$button_hover;
                   8058: }
                   8059: 
1.870     tempelho 8060: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8061:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8062:   color:$font;
1.957     onken    8063:   border: 0;
1.741     harmsja  8064: }
1.693     droeschl 8065: 
1.870     tempelho 8066: 
1.862     bisitz   8067: ul.LC_CourseBreadcrumbs {
                   8068:   background: $sidebg;
1.1020    raeburn  8069:   height: 2em;
1.862     bisitz   8070:   padding-left: 10px;
1.1020    raeburn  8071:   margin: 0;
1.862     bisitz   8072:   list-style-position: inside;
                   8073: }
                   8074: 
1.911     bisitz   8075: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8076: ol#LC_PathBreadcrumbs {
1.911     bisitz   8077:   padding-left: 10px;
                   8078:   margin: 0;
1.933     droeschl 8079:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8080: }
                   8081: 
1.911     bisitz   8082: ol#LC_MenuBreadcrumbs li,
                   8083: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8084: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8085:   display: inline;
1.933     droeschl 8086:   white-space: normal;  
1.693     droeschl 8087: }
                   8088: 
1.823     bisitz   8089: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8090: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8091:   text-decoration: none;
                   8092:   font-size:90%;
1.693     droeschl 8093: }
1.795     www      8094: 
1.969     droeschl 8095: ol#LC_MenuBreadcrumbs h1 {
                   8096:   display: inline;
                   8097:   font-size: 90%;
                   8098:   line-height: 2.5em;
                   8099:   margin: 0;
                   8100:   padding: 0;
                   8101: }
                   8102: 
1.795     www      8103: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8104:   text-decoration:none;
                   8105:   font-size:100%;
                   8106:   font-weight:bold;
1.693     droeschl 8107: }
1.795     www      8108: 
1.840     bisitz   8109: .LC_Box {
1.911     bisitz   8110:   border: solid 1px $lg_border_color;
                   8111:   padding: 0 10px 10px 10px;
1.746     neumanie 8112: }
1.795     www      8113: 
1.1020    raeburn  8114: .LC_DocsBox {
                   8115:   border: solid 1px $lg_border_color;
                   8116:   padding: 0 0 10px 10px;
                   8117: }
                   8118: 
1.795     www      8119: .LC_AboutMe_Image {
1.911     bisitz   8120:   float:left;
                   8121:   margin-right:10px;
1.747     neumanie 8122: }
1.795     www      8123: 
                   8124: .LC_Clear_AboutMe_Image {
1.911     bisitz   8125:   clear:left;
1.747     neumanie 8126: }
1.795     www      8127: 
1.721     harmsja  8128: dl.LC_ListStyleClean dt {
1.911     bisitz   8129:   padding-right: 5px;
                   8130:   display: table-header-group;
1.693     droeschl 8131: }
                   8132: 
1.721     harmsja  8133: dl.LC_ListStyleClean dd {
1.911     bisitz   8134:   display: table-row;
1.693     droeschl 8135: }
                   8136: 
1.721     harmsja  8137: .LC_ListStyleClean,
                   8138: .LC_ListStyleSimple,
                   8139: .LC_ListStyleNormal,
1.795     www      8140: .LC_ListStyleSpecial {
1.911     bisitz   8141:   /* display:block; */
                   8142:   list-style-position: inside;
                   8143:   list-style-type: none;
                   8144:   overflow: hidden;
                   8145:   padding: 0;
1.693     droeschl 8146: }
                   8147: 
1.721     harmsja  8148: .LC_ListStyleSimple li,
                   8149: .LC_ListStyleSimple dd,
                   8150: .LC_ListStyleNormal li,
                   8151: .LC_ListStyleNormal dd,
                   8152: .LC_ListStyleSpecial li,
1.795     www      8153: .LC_ListStyleSpecial dd {
1.911     bisitz   8154:   margin: 0;
                   8155:   padding: 5px 5px 5px 10px;
                   8156:   clear: both;
1.693     droeschl 8157: }
                   8158: 
1.721     harmsja  8159: .LC_ListStyleClean li,
                   8160: .LC_ListStyleClean dd {
1.911     bisitz   8161:   padding-top: 0;
                   8162:   padding-bottom: 0;
1.693     droeschl 8163: }
                   8164: 
1.721     harmsja  8165: .LC_ListStyleSimple dd,
1.795     www      8166: .LC_ListStyleSimple li {
1.911     bisitz   8167:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8168: }
                   8169: 
1.721     harmsja  8170: .LC_ListStyleSpecial li,
                   8171: .LC_ListStyleSpecial dd {
1.911     bisitz   8172:   list-style-type: none;
                   8173:   background-color: RGB(220, 220, 220);
                   8174:   margin-bottom: 4px;
1.693     droeschl 8175: }
                   8176: 
1.721     harmsja  8177: table.LC_SimpleTable {
1.911     bisitz   8178:   margin:5px;
                   8179:   border:solid 1px $lg_border_color;
1.795     www      8180: }
1.693     droeschl 8181: 
1.721     harmsja  8182: table.LC_SimpleTable tr {
1.911     bisitz   8183:   padding: 0;
                   8184:   border:solid 1px $lg_border_color;
1.693     droeschl 8185: }
1.795     www      8186: 
                   8187: table.LC_SimpleTable thead {
1.911     bisitz   8188:   background:rgb(220,220,220);
1.693     droeschl 8189: }
                   8190: 
1.721     harmsja  8191: div.LC_columnSection {
1.911     bisitz   8192:   display: block;
                   8193:   clear: both;
                   8194:   overflow: hidden;
                   8195:   margin: 0;
1.693     droeschl 8196: }
                   8197: 
1.721     harmsja  8198: div.LC_columnSection>* {
1.911     bisitz   8199:   float: left;
                   8200:   margin: 10px 20px 10px 0;
                   8201:   overflow:hidden;
1.693     droeschl 8202: }
1.721     harmsja  8203: 
1.795     www      8204: table em {
1.911     bisitz   8205:   font-weight: bold;
                   8206:   font-style: normal;
1.748     schulted 8207: }
1.795     www      8208: 
1.779     bisitz   8209: table.LC_tableBrowseRes,
1.795     www      8210: table.LC_tableOfContent {
1.911     bisitz   8211:   border:none;
                   8212:   border-spacing: 1px;
                   8213:   padding: 3px;
                   8214:   background-color: #FFFFFF;
                   8215:   font-size: 90%;
1.753     droeschl 8216: }
1.789     droeschl 8217: 
1.911     bisitz   8218: table.LC_tableOfContent {
                   8219:   border-collapse: collapse;
1.789     droeschl 8220: }
                   8221: 
1.771     droeschl 8222: table.LC_tableBrowseRes a,
1.768     schulted 8223: table.LC_tableOfContent a {
1.911     bisitz   8224:   background-color: transparent;
                   8225:   text-decoration: none;
1.753     droeschl 8226: }
                   8227: 
1.795     www      8228: table.LC_tableOfContent img {
1.911     bisitz   8229:   border: none;
                   8230:   height: 1.3em;
                   8231:   vertical-align: text-bottom;
                   8232:   margin-right: 0.3em;
1.753     droeschl 8233: }
1.757     schulted 8234: 
1.795     www      8235: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8236:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8237: }
                   8238: 
1.795     www      8239: a#LC_content_toolbar_everything {
1.911     bisitz   8240:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8241: }
                   8242: 
1.795     www      8243: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8244:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8245: }
                   8246: 
1.795     www      8247: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8248:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8249: }
                   8250: 
1.795     www      8251: a#LC_content_toolbar_changefolder {
1.911     bisitz   8252:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8253: }
                   8254: 
1.795     www      8255: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8256:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8257: }
                   8258: 
1.1043    raeburn  8259: a#LC_content_toolbar_edittoplevel {
                   8260:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8261: }
                   8262: 
1.795     www      8263: ul#LC_toolbar li a:hover {
1.911     bisitz   8264:   background-position: bottom center;
1.757     schulted 8265: }
                   8266: 
1.795     www      8267: ul#LC_toolbar {
1.911     bisitz   8268:   padding: 0;
                   8269:   margin: 2px;
                   8270:   list-style:none;
                   8271:   position:relative;
                   8272:   background-color:white;
1.1082    raeburn  8273:   overflow: auto;
1.757     schulted 8274: }
                   8275: 
1.795     www      8276: ul#LC_toolbar li {
1.911     bisitz   8277:   border:1px solid white;
                   8278:   padding: 0;
                   8279:   margin: 0;
                   8280:   float: left;
                   8281:   display:inline;
                   8282:   vertical-align:middle;
1.1082    raeburn  8283:   white-space: nowrap;
1.911     bisitz   8284: }
1.757     schulted 8285: 
1.783     amueller 8286: 
1.795     www      8287: a.LC_toolbarItem {
1.911     bisitz   8288:   display:block;
                   8289:   padding: 0;
                   8290:   margin: 0;
                   8291:   height: 32px;
                   8292:   width: 32px;
                   8293:   color:white;
                   8294:   border: none;
                   8295:   background-repeat:no-repeat;
                   8296:   background-color:transparent;
1.757     schulted 8297: }
                   8298: 
1.915     droeschl 8299: ul.LC_funclist {
                   8300:     margin: 0;
                   8301:     padding: 0.5em 1em 0.5em 0;
                   8302: }
                   8303: 
1.933     droeschl 8304: ul.LC_funclist > li:first-child {
                   8305:     font-weight:bold; 
                   8306:     margin-left:0.8em;
                   8307: }
                   8308: 
1.915     droeschl 8309: ul.LC_funclist + ul.LC_funclist {
                   8310:     /* 
                   8311:        left border as a seperator if we have more than
                   8312:        one list 
                   8313:     */
                   8314:     border-left: 1px solid $sidebg;
                   8315:     /* 
                   8316:        this hides the left border behind the border of the 
                   8317:        outer box if element is wrapped to the next 'line' 
                   8318:     */
                   8319:     margin-left: -1px;
                   8320: }
                   8321: 
1.843     bisitz   8322: ul.LC_funclist li {
1.915     droeschl 8323:   display: inline;
1.782     bisitz   8324:   white-space: nowrap;
1.915     droeschl 8325:   margin: 0 0 0 25px;
                   8326:   line-height: 150%;
1.782     bisitz   8327: }
                   8328: 
1.974     wenzelju 8329: .LC_hidden {
                   8330:   display: none;
                   8331: }
                   8332: 
1.1030    www      8333: .LCmodal-overlay {
                   8334: 		position:fixed;
                   8335: 		top:0;
                   8336: 		right:0;
                   8337: 		bottom:0;
                   8338: 		left:0;
                   8339: 		height:100%;
                   8340: 		width:100%;
                   8341: 		margin:0;
                   8342: 		padding:0;
                   8343: 		background:#999;
                   8344: 		opacity:.75;
                   8345: 		filter: alpha(opacity=75);
                   8346: 		-moz-opacity: 0.75;
                   8347: 		z-index:101;
                   8348: }
                   8349: 
                   8350: * html .LCmodal-overlay {   
                   8351: 		position: absolute;
                   8352: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8353: }
                   8354: 
                   8355: .LCmodal-window {
                   8356: 		position:fixed;
                   8357: 		top:50%;
                   8358: 		left:50%;
                   8359: 		margin:0;
                   8360: 		padding:0;
                   8361: 		z-index:102;
                   8362: 	}
                   8363: 
                   8364: * html .LCmodal-window {
                   8365: 		position:absolute;
                   8366: }
                   8367: 
                   8368: .LCclose-window {
                   8369: 		position:absolute;
                   8370: 		width:32px;
                   8371: 		height:32px;
                   8372: 		right:8px;
                   8373: 		top:8px;
                   8374: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8375: 		text-indent:-99999px;
                   8376: 		overflow:hidden;
                   8377: 		cursor:pointer;
                   8378: }
                   8379: 
1.1369  ! raeburn  8380: .LCisDisabled {
        !          8381:   cursor: not-allowed;
        !          8382:   opacity: 0.5;
        !          8383: }
        !          8384: 
        !          8385: a[aria-disabled="true"] {
        !          8386:   color: currentColor;
        !          8387:   display: inline-block;  /* For IE11/ MS Edge bug */
        !          8388:   pointer-events: none;
        !          8389:   text-decoration: none;
        !          8390: }
        !          8391: 
1.1335    raeburn  8392: pre.LC_wordwrap {
                   8393:   white-space: pre-wrap;
                   8394:   white-space: -moz-pre-wrap;
                   8395:   white-space: -pre-wrap;
                   8396:   white-space: -o-pre-wrap;
                   8397:   word-wrap: break-word;
                   8398: }
                   8399: 
1.1100    raeburn  8400: /*
1.1231    damieng  8401:   styles used for response display
                   8402: */
                   8403: div.LC_radiofoil, div.LC_rankfoil {
                   8404:   margin: .5em 0em .5em 0em;
                   8405: }
                   8406: table.LC_itemgroup {
                   8407:   margin-top: 1em;
                   8408: }
                   8409: 
                   8410: /*
1.1100    raeburn  8411:   styles used by TTH when "Default set of options to pass to tth/m
                   8412:   when converting TeX" in course settings has been set
                   8413: 
                   8414:   option passed: -t
                   8415: 
                   8416: */
                   8417: 
                   8418: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8419: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8420: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8421: td div.norm {line-height:normal;}
                   8422: 
                   8423: /*
                   8424:   option passed -y3
                   8425: */
                   8426: 
                   8427: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8428: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8429: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8430: 
1.1230    damieng  8431: /*
                   8432:   sections with roles, for content only
                   8433: */
                   8434: section[class^="role-"] {
                   8435:   padding-left: 10px;
                   8436:   padding-right: 5px;
                   8437:   margin-top: 8px;
                   8438:   margin-bottom: 8px;
                   8439:   border: 1px solid #2A4;
                   8440:   border-radius: 5px;
                   8441:   box-shadow: 0px 1px 1px #BBB;
                   8442: }
                   8443: section[class^="role-"]>h1 {
                   8444:   position: relative;
                   8445:   margin: 0px;
                   8446:   padding-top: 10px;
                   8447:   padding-left: 40px;
                   8448: }
                   8449: section[class^="role-"]>h1:before {
                   8450:   position: absolute;
                   8451:   left: -5px;
                   8452:   top: 5px;
                   8453: }
                   8454: section.role-activity>h1:before {
                   8455:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8456: }
                   8457: section.role-advice>h1:before {
                   8458:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8459: }
                   8460: section.role-bibliography>h1:before {
                   8461:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8462: }
                   8463: section.role-citation>h1:before {
                   8464:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8465: }
                   8466: section.role-conclusion>h1:before {
                   8467:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8468: }
                   8469: section.role-definition>h1:before {
                   8470:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8471: }
                   8472: section.role-demonstration>h1:before {
                   8473:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8474: }
                   8475: section.role-example>h1:before {
                   8476:   content:url('/adm/daxe/images/section_icons/example.png');
                   8477: }
                   8478: section.role-explanation>h1:before {
                   8479:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8480: }
                   8481: section.role-introduction>h1:before {
                   8482:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8483: }
                   8484: section.role-method>h1:before {
                   8485:   content:url('/adm/daxe/images/section_icons/method.png');
                   8486: }
                   8487: section.role-more_information>h1:before {
                   8488:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8489: }
                   8490: section.role-objectives>h1:before {
                   8491:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8492: }
                   8493: section.role-prerequisites>h1:before {
                   8494:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8495: }
                   8496: section.role-remark>h1:before {
                   8497:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8498: }
                   8499: section.role-reminder>h1:before {
                   8500:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8501: }
                   8502: section.role-summary>h1:before {
                   8503:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8504: }
                   8505: section.role-syntax>h1:before {
                   8506:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8507: }
                   8508: section.role-warning>h1:before {
                   8509:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8510: }
                   8511: 
1.1269    raeburn  8512: #LC_minitab_header {
                   8513:   float:left;
                   8514:   width:100%;
                   8515:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8516:   font-size:93%;
                   8517:   line-height:normal;
                   8518:   margin: 0.5em 0 0.5em 0;
                   8519: }
                   8520: #LC_minitab_header ul {
                   8521:   margin:0;
                   8522:   padding:10px 10px 0;
                   8523:   list-style:none;
                   8524: }
                   8525: #LC_minitab_header li {
                   8526:   float:left;
                   8527:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8528:   margin:0;
                   8529:   padding:0 0 0 9px;
                   8530: }
                   8531: #LC_minitab_header a {
                   8532:   display:block;
                   8533:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8534:   padding:5px 15px 4px 6px;
                   8535: }
                   8536: #LC_minitab_header #LC_current_minitab {
                   8537:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8538: }
                   8539: #LC_minitab_header #LC_current_minitab a {
                   8540:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8541:   padding-bottom:5px;
                   8542: }
                   8543: 
                   8544: 
1.343     albertel 8545: END
                   8546: }
                   8547: 
1.306     albertel 8548: =pod
                   8549: 
                   8550: =item * &headtag()
                   8551: 
                   8552: Returns a uniform footer for LON-CAPA web pages.
                   8553: 
1.307     albertel 8554: Inputs: $title - optional title for the head
                   8555:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8556:         $args - optional arguments
1.319     albertel 8557:             force_register - if is true call registerurl so the remote is 
                   8558:                              informed
1.415     albertel 8559:             redirect       -> array ref of
                   8560:                                    1- seconds before redirect occurs
                   8561:                                    2- url to redirect to
                   8562:                                    3- whether the side effect should occur
1.315     albertel 8563:                            (side effect of setting 
                   8564:                                $env{'internal.head.redirect'} to the url 
                   8565:                                redirected too)
1.352     albertel 8566:             domain         -> force to color decorate a page for a specific
                   8567:                                domain
                   8568:             function       -> force usage of a specific rolish color scheme
                   8569:             bgcolor        -> override the default page bgcolor
1.460     albertel 8570:             no_auto_mt_title
                   8571:                            -> prevent &mt()ing the title arg
1.464     albertel 8572: 
1.306     albertel 8573: =cut
                   8574: 
                   8575: sub headtag {
1.313     albertel 8576:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8577:     
1.363     albertel 8578:     my $function = $args->{'function'} || &get_users_function();
                   8579:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8580:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8581:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8582:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8583: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8584: 		   #time(),
1.418     albertel 8585: 		   $env{'environment.color.timestamp'},
1.363     albertel 8586: 		   $function,$domain,$bgcolor);
                   8587: 
1.369     www      8588:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8589: 
1.308     albertel 8590:     my $result =
                   8591: 	'<head>'.
1.1160    raeburn  8592: 	&font_settings($args);
1.319     albertel 8593: 
1.1188    raeburn  8594:     my $inhibitprint;
                   8595:     if ($args->{'print_suppress'}) {
                   8596:         $inhibitprint = &print_suppression();
                   8597:     }
1.1064    raeburn  8598: 
1.461     albertel 8599:     if (!$args->{'frameset'}) {
                   8600: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8601:     }
1.962     droeschl 8602:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8603:         $result .= Apache::lonxml::display_title();
1.319     albertel 8604:     }
1.436     albertel 8605:     if (!$args->{'no_nav_bar'} 
                   8606: 	&& !$args->{'only_body'}
                   8607: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8608: 	$result .= &help_menu_js($httphost);
1.1032    www      8609:         $result.=&modal_window();
1.1038    www      8610:         $result.=&togglebox_script();
1.1034    www      8611:         $result.=&wishlist_window();
1.1041    www      8612:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8613:     } else {
                   8614:         if ($args->{'add_modal'}) {
                   8615:            $result.=&modal_window();
                   8616:         }
                   8617:         if ($args->{'add_wishlist'}) {
                   8618:            $result.=&wishlist_window();
                   8619:         }
1.1038    www      8620:         if ($args->{'add_togglebox'}) {
                   8621:            $result.=&togglebox_script();
                   8622:         }
1.1041    www      8623:         if ($args->{'add_progressbar'}) {
                   8624:            $result.=&LCprogressbarUpdate_script();
                   8625:         }
1.436     albertel 8626:     }
1.314     albertel 8627:     if (ref($args->{'redirect'})) {
1.414     albertel 8628: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8629: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8630: 	if (!$inhibit_continue) {
                   8631: 	    $env{'internal.head.redirect'} = $url;
                   8632: 	}
1.313     albertel 8633: 	$result.=<<ADDMETA
                   8634: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8635: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8636: ADDMETA
1.1210    raeburn  8637:     } else {
                   8638:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8639:             my $requrl = $env{'request.uri'};
                   8640:             if ($requrl eq '') {
                   8641:                 $requrl = $ENV{'REQUEST_URI'};
                   8642:                 $requrl =~ s/\?.+$//;
                   8643:             }
                   8644:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8645:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8646:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8647:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8648:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8649:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8650:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  8651:                     my ($offload,$offloadoth);
1.1210    raeburn  8652:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8653:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8654:                             $offload = 1;
1.1353    raeburn  8655:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8656:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8657:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8658:                                     $offloadoth = 1;
                   8659:                                     $dom_in_use = $env{'user.domain'};
                   8660:                                 }
                   8661:                             }
1.1340    raeburn  8662:                         }
                   8663:                     }
                   8664:                     unless ($offload) {
                   8665:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8666:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8667:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8668:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8669:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8670:                                         $offload = 1;
1.1352    raeburn  8671:                                         $offloadoth = 1;
1.1340    raeburn  8672:                                         $dom_in_use = $env{'user.domain'};
                   8673:                                     }
1.1210    raeburn  8674:                                 }
1.1340    raeburn  8675:                             }
                   8676:                         }
                   8677:                     }
                   8678:                     if ($offload) {
1.1358    raeburn  8679:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  8680:                         if (($newserver eq '') && ($offloadoth)) {
                   8681:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8682:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8683:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8684:                             }
                   8685:                         }
1.1340    raeburn  8686:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8687:                             my $numsec = 5;
                   8688:                             my $timeout = $numsec * 1000;
                   8689:                             my ($newurl,$locknum,%locks,$msg);
                   8690:                             if ($env{'request.role.adv'}) {
                   8691:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8692:                             }
                   8693:                             my $disable_submit = 0;
                   8694:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8695:                                 $disable_submit = 1;
                   8696:                             }
                   8697:                             if ($locknum) {
                   8698:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  8699:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  8700:                                        join(", ",sort(values(%locks)))."\n";
                   8701:                                 if (&show_course()) {
                   8702:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8703:                                 } else {
                   8704:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8705:                                 }
1.1340    raeburn  8706:                             } else {
                   8707:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8708:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8709:                                 }
                   8710:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8711:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8712:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8713:                                     $newurl .= '&role='.$env{'request.role'};
                   8714:                                 }
                   8715:                                 if ($env{'request.symb'}) {
                   8716:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8717:                                     if ($shownsymb =~ m{^/enc/}) {
                   8718:                                         my $reqdmajor = 2;
                   8719:                                         my $reqdminor = 11;
                   8720:                                         my $reqdsubminor = 3;
                   8721:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8722:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8723:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8724:                                         if (($major eq '' && $minor eq '') ||
                   8725:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8726:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8727:                                              ($reqdsubminor > $subminor))))) {
                   8728:                                             undef($shownsymb);
                   8729:                                         }
1.1210    raeburn  8730:                                     }
1.1340    raeburn  8731:                                     if ($shownsymb) {
                   8732:                                         &js_escape(\$shownsymb);
                   8733:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  8734:                                     }
1.1340    raeburn  8735:                                 } else {
                   8736:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8737:                                     &js_escape(\$shownurl);
                   8738:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  8739:                                 }
1.1340    raeburn  8740:                             }
                   8741:                             &js_escape(\$msg);
                   8742:                             $result.=<<OFFLOAD
1.1210    raeburn  8743: <meta http-equiv="pragma" content="no-cache" />
                   8744: <script type="text/javascript">
1.1215    raeburn  8745: // <![CDATA[
1.1210    raeburn  8746: function LC_Offload_Now() {
                   8747:     var dest = "$newurl";
                   8748:     if (dest != '') {
                   8749:         window.location.href="$newurl";
                   8750:     }
                   8751: }
1.1214    raeburn  8752: \$(document).ready(function () {
                   8753:     window.alert('$msg');
                   8754:     if ($disable_submit) {
1.1210    raeburn  8755:         \$(".LC_hwk_submit").prop("disabled", true);
                   8756:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8757:     }
                   8758:     setTimeout('LC_Offload_Now()', $timeout);
                   8759: });
1.1215    raeburn  8760: // ]]>
1.1210    raeburn  8761: </script>
                   8762: OFFLOAD
                   8763:                         }
                   8764:                     }
                   8765:                 }
                   8766:             }
                   8767:         }
1.313     albertel 8768:     }
1.306     albertel 8769:     if (!defined($title)) {
                   8770: 	$title = 'The LearningOnline Network with CAPA';
                   8771:     }
1.460     albertel 8772:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8773:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8774: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8775:     if (!$args->{'frameset'}) {
                   8776:         $result .= ' /';
                   8777:     }
                   8778:     $result .= '>' 
1.1064    raeburn  8779:         .$inhibitprint
1.414     albertel 8780: 	.$head_extra;
1.1242    raeburn  8781:     my $clientmobile;
                   8782:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8783:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8784:     } else {
                   8785:         $clientmobile = $env{'browser.mobile'};
                   8786:     }
                   8787:     if ($clientmobile) {
1.1137    raeburn  8788:         $result .= '
                   8789: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8790: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8791:     }
1.1278    raeburn  8792:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8793:     return $result.'</head>';
1.306     albertel 8794: }
                   8795: 
                   8796: =pod
                   8797: 
1.340     albertel 8798: =item * &font_settings()
                   8799: 
                   8800: Returns neccessary <meta> to set the proper encoding
                   8801: 
1.1160    raeburn  8802: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8803: 
                   8804: =cut
                   8805: 
                   8806: sub font_settings {
1.1160    raeburn  8807:     my ($args) = @_;
1.340     albertel 8808:     my $headerstring='';
1.1160    raeburn  8809:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8810:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8811:         $headerstring.=
                   8812:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8813:         if (!$args->{'frameset'}) {
                   8814: 	    $headerstring.= ' /';
                   8815:         }
                   8816: 	$headerstring .= '>'."\n";
1.340     albertel 8817:     }
                   8818:     return $headerstring;
                   8819: }
                   8820: 
1.341     albertel 8821: =pod
                   8822: 
1.1064    raeburn  8823: =item * &print_suppression()
                   8824: 
                   8825: In course context returns css which causes the body to be blank when media="print",
                   8826: if printout generation is unavailable for the current resource.
                   8827: 
                   8828: This could be because:
                   8829: 
                   8830: (a) printstartdate is in the future
                   8831: 
                   8832: (b) printenddate is in the past
                   8833: 
                   8834: (c) there is an active exam block with "printout"
                   8835: functionality blocked
                   8836: 
                   8837: Users with pav, pfo or evb privileges are exempt.
                   8838: 
                   8839: Inputs: none
                   8840: 
                   8841: =cut
                   8842: 
                   8843: 
                   8844: sub print_suppression {
                   8845:     my $noprint;
                   8846:     if ($env{'request.course.id'}) {
                   8847:         my $scope = $env{'request.course.id'};
                   8848:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8849:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8850:             return;
                   8851:         }
                   8852:         if ($env{'request.course.sec'} ne '') {
                   8853:             $scope .= "/$env{'request.course.sec'}";
                   8854:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8855:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8856:                 return;
1.1064    raeburn  8857:             }
                   8858:         }
                   8859:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8860:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8861:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8862:         if ($blocked) {
                   8863:             my $checkrole = "cm./$cdom/$cnum";
                   8864:             if ($env{'request.course.sec'} ne '') {
                   8865:                 $checkrole .= "/$env{'request.course.sec'}";
                   8866:             }
                   8867:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8868:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8869:                 $noprint = 1;
                   8870:             }
                   8871:         }
                   8872:         unless ($noprint) {
                   8873:             my $symb = &Apache::lonnet::symbread();
                   8874:             if ($symb ne '') {
                   8875:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8876:                 if (ref($navmap)) {
                   8877:                     my $res = $navmap->getBySymb($symb);
                   8878:                     if (ref($res)) {
                   8879:                         if (!$res->resprintable()) {
                   8880:                             $noprint = 1;
                   8881:                         }
                   8882:                     }
                   8883:                 }
                   8884:             }
                   8885:         }
                   8886:         if ($noprint) {
                   8887:             return <<"ENDSTYLE";
                   8888: <style type="text/css" media="print">
                   8889:     body { display:none }
                   8890: </style>
                   8891: ENDSTYLE
                   8892:         }
                   8893:     }
                   8894:     return;
                   8895: }
                   8896: 
                   8897: =pod
                   8898: 
1.341     albertel 8899: =item * &xml_begin()
                   8900: 
                   8901: Returns the needed doctype and <html>
                   8902: 
                   8903: Inputs: none
                   8904: 
                   8905: =cut
                   8906: 
                   8907: sub xml_begin {
1.1168    raeburn  8908:     my ($is_frameset) = @_;
1.341     albertel 8909:     my $output='';
                   8910: 
                   8911:     if ($env{'browser.mathml'}) {
                   8912: 	$output='<?xml version="1.0"?>'
                   8913:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8914: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8915:             
                   8916: #	    .'<!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">] >'
                   8917: 	    .'<!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">'
                   8918:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8919: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8920:     } elsif ($is_frameset) {
                   8921:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8922:                 '<html>'."\n";
1.341     albertel 8923:     } else {
1.1168    raeburn  8924: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8925:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8926:     }
                   8927:     return $output;
                   8928: }
1.340     albertel 8929: 
                   8930: =pod
                   8931: 
1.306     albertel 8932: =item * &start_page()
                   8933: 
                   8934: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8935: 
1.648     raeburn  8936: Inputs:
                   8937: 
                   8938: =over 4
                   8939: 
                   8940: $title - optional title for the page
                   8941: 
                   8942: $head_extra - optional extra HTML to incude inside the <head>
                   8943: 
                   8944: $args - additional optional args supported are:
                   8945: 
                   8946: =over 8
                   8947: 
                   8948:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8949:                                     arg on
1.814     bisitz   8950:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8951:              add_entries    -> additional attributes to add to the  <body>
                   8952:              domain         -> force to color decorate a page for a 
1.317     albertel 8953:                                     specific domain
1.648     raeburn  8954:              function       -> force usage of a specific rolish color
1.317     albertel 8955:                                     scheme
1.648     raeburn  8956:              redirect       -> see &headtag()
                   8957:              bgcolor        -> override the default page bg color
                   8958:              js_ready       -> return a string ready for being used in 
1.317     albertel 8959:                                     a javascript writeln
1.648     raeburn  8960:              html_encode    -> return a string ready for being used in 
1.320     albertel 8961:                                     a html attribute
1.648     raeburn  8962:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8963:                                     $forcereg arg
1.648     raeburn  8964:              frameset       -> if true will start with a <frameset>
1.330     albertel 8965:                                     rather than <body>
1.648     raeburn  8966:              skip_phases    -> hash ref of 
1.338     albertel 8967:                                     head -> skip the <html><head> generation
                   8968:                                     body -> skip all <body> generation
1.648     raeburn  8969:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8970:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8971:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8972:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8973:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8974:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8975:                                specific group
                   8976:              use_absolute   -> for request for external resource or syllabus, this
                   8977:                                will contain https://<hostname> if server uses
                   8978:                                https (as per hosts.tab), but request is for http
                   8979:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369  ! raeburn  8980:              links_disabled -> Links in primary and secondary menus are disabled
        !          8981:                                (Can enable them once page has loaded - see lonroles.pm
        !          8982:                                for an example).
1.361     albertel 8983: 
1.648     raeburn  8984: =back
1.460     albertel 8985: 
1.648     raeburn  8986: =back
1.562     albertel 8987: 
1.306     albertel 8988: =cut
                   8989: 
                   8990: sub start_page {
1.309     albertel 8991:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8992:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8993: 
1.315     albertel 8994:     $env{'internal.start_page'}++;
1.1359    raeburn  8995:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 8996: 
1.338     albertel 8997:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8998:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8999:     }
1.1316    raeburn  9000: 
                   9001:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9002:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9003:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9004:                 $args->{'no_primary_menu'} = 1;
                   9005:             }
                   9006:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9007:                 $args->{'no_inline_menu'} = 1;
                   9008:             }
                   9009:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9010:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9011:             }
                   9012:         } else {
                   9013:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9014:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9015:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9016:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9017:                     $args->{'no_primary_menu'} = 1;
                   9018:                 }
                   9019:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9020:                     $args->{'no_inline_menu'} = 1;
                   9021:                 }
                   9022:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9023:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9024:                 }
                   9025:             }
                   9026:         }
1.1316    raeburn  9027:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9028:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9029:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9030:     } elsif ($env{'request.course.id'}) {
                   9031:         my $expiretime=600;
                   9032:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9033:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9034:         }
                   9035:         my ($deeplinkmenu,$menuref);
                   9036:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9037:         if ($menucoll) {
                   9038:             if (ref($menuref) eq 'HASH') {
                   9039:                 %menu = %{$menuref};
                   9040:             }
                   9041:             if ($menu{'top'} eq 'n') {
                   9042:                 $args->{'no_primary_menu'} = 1;
                   9043:             }
                   9044:             if ($menu{'inline'} eq 'n') {
                   9045:                 unless (&Apache::lonnet::allowed('opa')) {
                   9046:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9047:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9048:                     my $crstype = &course_type();
                   9049:                     my $now = time;
                   9050:                     my $ccrole;
                   9051:                     if ($crstype eq 'Community') {
                   9052:                         $ccrole = 'co';
                   9053:                     } else {
                   9054:                         $ccrole = 'cc';
                   9055:                     }
                   9056:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9057:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9058:                         if ((($start) && ($start<0)) ||
                   9059:                             (($end) && ($end<$now))  ||
                   9060:                             (($start) && ($now<$start))) {
                   9061:                             $args->{'no_inline_menu'} = 1;
                   9062:                         }
                   9063:                     } else {
                   9064:                         $args->{'no_inline_menu'} = 1;
                   9065:                     }
                   9066:                 }
                   9067:             }
                   9068:         }
1.1316    raeburn  9069:     }
1.1359    raeburn  9070: 
1.338     albertel 9071:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9072: 	if ($args->{'frameset'}) {
                   9073: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9074: 						$args->{'add_entries'});
                   9075: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9076:         } else {
                   9077:             $result .=
                   9078:                 &bodytag($title, 
                   9079:                          $args->{'function'},       $args->{'add_entries'},
                   9080:                          $args->{'only_body'},      $args->{'domain'},
                   9081:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9082:                          $args->{'bgcolor'},        $args,
1.1359    raeburn  9083:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
1.831     bisitz   9084:         }
1.330     albertel 9085:     }
1.338     albertel 9086: 
1.315     albertel 9087:     if ($args->{'js_ready'}) {
1.713     kaisler  9088: 		$result = &js_ready($result);
1.315     albertel 9089:     }
1.320     albertel 9090:     if ($args->{'html_encode'}) {
1.713     kaisler  9091: 		$result = &html_encode($result);
                   9092:     }
                   9093: 
1.813     bisitz   9094:     # Preparation for new and consistent functionlist at top of screen
                   9095:     # if ($args->{'functionlist'}) {
                   9096:     #            $result .= &build_functionlist();
                   9097:     #}
                   9098: 
1.964     droeschl 9099:     # Don't add anything more if only_body wanted or in const space
                   9100:     return $result if    $args->{'only_body'} 
                   9101:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9102: 
                   9103:     #Breadcrumbs
1.758     kaisler  9104:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   9105: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9106: 		#if any br links exists, add them to the breadcrumbs
                   9107: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9108: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9109: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9110: 			}
                   9111: 		}
1.1096    raeburn  9112:                 # if @advtools array contains items add then to the breadcrumbs
                   9113:                 if (@advtools > 0) {
                   9114:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9115:                 }
1.1272    raeburn  9116:                 my $menulink;
                   9117:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9118:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9119:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9120:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9121:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9122:                      (!$env{'request.role.adv'}))) {
                   9123:                     $menulink = 0;
                   9124:                 } else {
                   9125:                     undef($menulink);
                   9126:                 }
1.758     kaisler  9127: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9128: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9129: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9130:                 } else {
1.1272    raeburn  9131: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9132: 		}
1.320     albertel 9133:     }
1.315     albertel 9134:     return $result;
1.306     albertel 9135: }
                   9136: 
                   9137: sub end_page {
1.315     albertel 9138:     my ($args) = @_;
                   9139:     $env{'internal.end_page'}++;
1.330     albertel 9140:     my $result;
1.335     albertel 9141:     if ($args->{'discussion'}) {
                   9142: 	my ($target,$parser);
                   9143: 	if (ref($args->{'discussion'})) {
                   9144: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9145: 				$args->{'discussion'}{'parser'});
                   9146: 	}
                   9147: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9148:     }
1.330     albertel 9149:     if ($args->{'frameset'}) {
                   9150: 	$result .= '</frameset>';
                   9151:     } else {
1.635     raeburn  9152: 	$result .= &endbodytag($args);
1.330     albertel 9153:     }
1.1080    raeburn  9154:     unless ($args->{'notbody'}) {
                   9155:         $result .= "\n</html>";
                   9156:     }
1.330     albertel 9157: 
1.315     albertel 9158:     if ($args->{'js_ready'}) {
1.317     albertel 9159: 	$result = &js_ready($result);
1.315     albertel 9160:     }
1.335     albertel 9161: 
1.320     albertel 9162:     if ($args->{'html_encode'}) {
                   9163: 	$result = &html_encode($result);
                   9164:     }
1.335     albertel 9165: 
1.315     albertel 9166:     return $result;
                   9167: }
                   9168: 
1.1359    raeburn  9169: sub menucoll_in_effect {
                   9170:     my ($menucoll,$deeplinkmenu,%menu);
                   9171:     if ($env{'request.course.id'}) {
                   9172:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9173:         if ($env{'request.deeplink.login'}) {
                   9174:             my ($deeplink_symb,$deeplink);
                   9175:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9176:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9177:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9178:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9179:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9180:                     if (ref($navmap)) {
                   9181:                         $deeplink = $navmap->get_mapparam(undef,
                   9182:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9183:                                                           '0.deeplink');
                   9184:                     }
                   9185:                 } else {
                   9186:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink');
                   9187:                 }
                   9188:             } else {
                   9189:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9190:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9191:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9192:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9193:                     if (ref($navmap)) {
                   9194:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9195:                     }
                   9196:                 } else {
                   9197:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9198:                 }
                   9199:             }
1.1359    raeburn  9200:             if ($deeplink ne '') {
1.1363    raeburn  9201:                 my ($state,$others,$listed,$scope,$protect,$display) = split(/,/,$deeplink);
1.1359    raeburn  9202:                 if ($display =~ /^\d+$/) {
                   9203:                     $deeplinkmenu = 1;
                   9204:                     $menucoll = $display;
                   9205:                 }
                   9206:             }
                   9207:         }
                   9208:         if ($menucoll) {
                   9209:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9210:         }
                   9211:     }
                   9212:     return ($menucoll,$deeplinkmenu,\%menu);
                   9213: }
                   9214: 
1.1362    raeburn  9215: sub deeplink_login_symb {
                   9216:     my ($cnum,$cdom) = @_;
                   9217:     my $login_symb;
                   9218:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9219:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9220:     }
                   9221:     return $login_symb;
                   9222: }
                   9223: 
                   9224: sub symb_from_tinyurl {
                   9225:     my ($url,$cnum,$cdom) = @_;
                   9226:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9227:         my $key = $1;
                   9228:         my ($tinyurl,$login);
                   9229:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9230:         if (defined($cached)) {
                   9231:             $tinyurl = $result;
                   9232:         } else {
                   9233:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9234:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9235:             if ($currtiny{$key} ne '') {
                   9236:                 $tinyurl = $currtiny{$key};
                   9237:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9238:             }
1.1364    raeburn  9239:         }
                   9240:         if ($tinyurl ne '') {
                   9241:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9242:             if (wantarray) {
                   9243:                 return ($cnumreq,$symb);
                   9244:             } elsif ($cnumreq eq $cnum) {
                   9245:                 return $symb;
1.1362    raeburn  9246:             }
                   9247:         }
                   9248:     }
1.1364    raeburn  9249:     if (wantarray) {
                   9250:         return ();
                   9251:     } else {
                   9252:         return;
                   9253:     }
1.1362    raeburn  9254: }
                   9255: 
1.1034    www      9256: sub wishlist_window {
                   9257:     return(<<'ENDWISHLIST');
1.1046    raeburn  9258: <script type="text/javascript">
1.1034    www      9259: // <![CDATA[
                   9260: // <!-- BEGIN LON-CAPA Internal
                   9261: function set_wishlistlink(title, path) {
                   9262:     if (!title) {
                   9263:         title = document.title;
                   9264:         title = title.replace(/^LON-CAPA /,'');
                   9265:     }
1.1175    raeburn  9266:     title = encodeURIComponent(title);
1.1203    raeburn  9267:     title = title.replace("'","\\\'");
1.1034    www      9268:     if (!path) {
                   9269:         path = location.pathname;
                   9270:     }
1.1175    raeburn  9271:     path = encodeURIComponent(path);
1.1203    raeburn  9272:     path = path.replace("'","\\\'");
1.1034    www      9273:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9274:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9275: }
                   9276: // END LON-CAPA Internal -->
                   9277: // ]]>
                   9278: </script>
                   9279: ENDWISHLIST
                   9280: }
                   9281: 
1.1030    www      9282: sub modal_window {
                   9283:     return(<<'ENDMODAL');
1.1046    raeburn  9284: <script type="text/javascript">
1.1030    www      9285: // <![CDATA[
                   9286: // <!-- BEGIN LON-CAPA Internal
                   9287: var modalWindow = {
                   9288: 	parent:"body",
                   9289: 	windowId:null,
                   9290: 	content:null,
                   9291: 	width:null,
                   9292: 	height:null,
                   9293: 	close:function()
                   9294: 	{
                   9295: 	        $(".LCmodal-window").remove();
                   9296: 	        $(".LCmodal-overlay").remove();
                   9297: 	},
                   9298: 	open:function()
                   9299: 	{
                   9300: 		var modal = "";
                   9301: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9302: 		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;\">";
                   9303: 		modal += this.content;
                   9304: 		modal += "</div>";	
                   9305: 
                   9306: 		$(this.parent).append(modal);
                   9307: 
                   9308: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9309: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9310: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9311: 	}
                   9312: };
1.1140    raeburn  9313: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9314: 	{
1.1266    raeburn  9315:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9316: 		modalWindow.windowId = "myModal";
                   9317: 		modalWindow.width = width;
                   9318: 		modalWindow.height = height;
1.1196    raeburn  9319: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9320: 		modalWindow.open();
1.1208    raeburn  9321: 	};
1.1030    www      9322: // END LON-CAPA Internal -->
                   9323: // ]]>
                   9324: </script>
                   9325: ENDMODAL
                   9326: }
                   9327: 
                   9328: sub modal_link {
1.1140    raeburn  9329:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9330:     unless ($width) { $width=480; }
                   9331:     unless ($height) { $height=400; }
1.1031    www      9332:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9333:     unless ($transparency) { $transparency='true'; }
                   9334: 
1.1074    raeburn  9335:     my $target_attr;
                   9336:     if (defined($target)) {
                   9337:         $target_attr = 'target="'.$target.'"';
                   9338:     }
                   9339:     return <<"ENDLINK";
1.1336    raeburn  9340: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9341: ENDLINK
1.1030    www      9342: }
                   9343: 
1.1032    www      9344: sub modal_adhoc_script {
1.1365    raeburn  9345:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9346:     my $mathjax;
                   9347:     if ($possmathjax) {
                   9348:         $mathjax = <<'ENDJAX';
                   9349:                if (typeof MathJax == 'object') {
                   9350:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9351:                }
                   9352: ENDJAX
                   9353:     }
1.1032    www      9354:     return (<<ENDADHOC);
1.1046    raeburn  9355: <script type="text/javascript">
1.1032    www      9356: // <![CDATA[
                   9357:         var $funcname = function()
                   9358:         {
                   9359:                 modalWindow.windowId = "myModal";
                   9360:                 modalWindow.width = $width;
                   9361:                 modalWindow.height = $height;
                   9362:                 modalWindow.content = '$content';
                   9363:                 modalWindow.open();
1.1365    raeburn  9364:                 $mathjax
1.1032    www      9365:         };  
                   9366: // ]]>
                   9367: </script>
                   9368: ENDADHOC
                   9369: }
                   9370: 
1.1041    www      9371: sub modal_adhoc_inner {
1.1365    raeburn  9372:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9373:     my $innerwidth=$width-20;
                   9374:     $content=&js_ready(
1.1140    raeburn  9375:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9376:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9377:                  $content.
1.1041    www      9378:                  &end_scrollbox().
1.1140    raeburn  9379:                  &end_page()
1.1041    www      9380:              );
1.1365    raeburn  9381:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9382: }
                   9383: 
                   9384: sub modal_adhoc_window {
1.1365    raeburn  9385:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9386:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9387:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9388: }
                   9389: 
                   9390: sub modal_adhoc_launch {
                   9391:     my ($funcname,$width,$height,$content)=@_;
                   9392:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9393: <script type="text/javascript">
                   9394: // <![CDATA[
                   9395: $funcname();
                   9396: // ]]>
                   9397: </script>
                   9398: ENDLAUNCH
                   9399: }
                   9400: 
                   9401: sub modal_adhoc_close {
                   9402:     return (<<ENDCLOSE);
                   9403: <script type="text/javascript">
                   9404: // <![CDATA[
                   9405: modalWindow.close();
                   9406: // ]]>
                   9407: </script>
                   9408: ENDCLOSE
                   9409: }
                   9410: 
1.1038    www      9411: sub togglebox_script {
                   9412:    return(<<ENDTOGGLE);
                   9413: <script type="text/javascript"> 
                   9414: // <![CDATA[
                   9415: function LCtoggleDisplay(id,hidetext,showtext) {
                   9416:    link = document.getElementById(id + "link").childNodes[0];
                   9417:    with (document.getElementById(id).style) {
                   9418:       if (display == "none" ) {
                   9419:           display = "inline";
                   9420:           link.nodeValue = hidetext;
                   9421:         } else {
                   9422:           display = "none";
                   9423:           link.nodeValue = showtext;
                   9424:        }
                   9425:    }
                   9426: }
                   9427: // ]]>
                   9428: </script>
                   9429: ENDTOGGLE
                   9430: }
                   9431: 
1.1039    www      9432: sub start_togglebox {
                   9433:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9434:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9435:     unless ($showtext) { $showtext=&mt('show'); }
                   9436:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9437:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9438:     return &start_data_table().
                   9439:            &start_data_table_header_row().
                   9440:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9441:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9442:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9443:            &end_data_table_header_row().
                   9444:            '<tr id="'.$id.'" style="display:none""><td>';
                   9445: }
                   9446: 
                   9447: sub end_togglebox {
                   9448:     return '</td></tr>'.&end_data_table();
                   9449: }
                   9450: 
1.1041    www      9451: sub LCprogressbar_script {
1.1302    raeburn  9452:    my ($id,$number_to_do)=@_;
                   9453:    if ($number_to_do) {
                   9454:        return(<<ENDPROGRESS);
1.1041    www      9455: <script type="text/javascript">
                   9456: // <![CDATA[
1.1045    www      9457: \$('#progressbar$id').progressbar({
1.1041    www      9458:   value: 0,
                   9459:   change: function(event, ui) {
                   9460:     var newVal = \$(this).progressbar('option', 'value');
                   9461:     \$('.pblabel', this).text(LCprogressTxt);
                   9462:   }
                   9463: });
                   9464: // ]]>
                   9465: </script>
                   9466: ENDPROGRESS
1.1302    raeburn  9467:    } else {
                   9468:        return(<<ENDPROGRESS);
                   9469: <script type="text/javascript">
                   9470: // <![CDATA[
                   9471: \$('#progressbar$id').progressbar({
                   9472:   value: false,
                   9473:   create: function(event, ui) {
                   9474:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9475:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9476:   }
                   9477: });
                   9478: // ]]>
                   9479: </script>
                   9480: ENDPROGRESS
                   9481:    }
1.1041    www      9482: }
                   9483: 
                   9484: sub LCprogressbarUpdate_script {
                   9485:    return(<<ENDPROGRESSUPDATE);
                   9486: <style type="text/css">
                   9487: .ui-progressbar { position:relative; }
1.1302    raeburn  9488: .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      9489: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9490: </style>
                   9491: <script type="text/javascript">
                   9492: // <![CDATA[
1.1045    www      9493: var LCprogressTxt='---';
                   9494: 
1.1302    raeburn  9495: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9496:    LCprogressTxt=progresstext;
1.1302    raeburn  9497:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9498:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9499:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9500:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9501:    } else {
                   9502:        \$('#progressbar'+id).progressbar('value',percent);
                   9503:    }
1.1041    www      9504: }
                   9505: // ]]>
                   9506: </script>
                   9507: ENDPROGRESSUPDATE
                   9508: }
                   9509: 
1.1042    www      9510: my $LClastpercent;
1.1045    www      9511: my $LCidcnt;
                   9512: my $LCcurrentid;
1.1042    www      9513: 
1.1041    www      9514: sub LCprogressbar {
1.1302    raeburn  9515:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9516:     $LClastpercent=0;
1.1045    www      9517:     $LCidcnt++;
                   9518:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9519:     my ($starting,$content);
                   9520:     if ($number_to_do) {
                   9521:         $starting=&mt('Starting');
                   9522:         $content=(<<ENDPROGBAR);
                   9523: $preamble
1.1045    www      9524:   <div id="progressbar$LCcurrentid">
1.1041    www      9525:     <span class="pblabel">$starting</span>
                   9526:   </div>
                   9527: ENDPROGBAR
1.1302    raeburn  9528:     } else {
                   9529:         $starting=&mt('Loading...');
                   9530:         $LClastpercent='false';
                   9531:         $content=(<<ENDPROGBAR);
                   9532: $preamble
                   9533:   <div id="progressbar$LCcurrentid">
                   9534:       <div class="progress-label">$starting</div>
                   9535:   </div>
                   9536: ENDPROGBAR
                   9537:     }
                   9538:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9539: }
                   9540: 
                   9541: sub LCprogressbarUpdate {
1.1302    raeburn  9542:     my ($r,$val,$text,$number_to_do)=@_;
                   9543:     if ($number_to_do) {
                   9544:         unless ($val) { 
                   9545:             if ($LClastpercent) {
                   9546:                 $val=$LClastpercent;
                   9547:             } else {
                   9548:                 $val=0;
                   9549:             }
                   9550:         }
                   9551:         if ($val<0) { $val=0; }
                   9552:         if ($val>100) { $val=0; }
                   9553:         $LClastpercent=$val;
                   9554:         unless ($text) { $text=$val.'%'; }
                   9555:     } else {
                   9556:         $val = 'false';
1.1042    www      9557:     }
1.1041    www      9558:     $text=&js_ready($text);
1.1044    www      9559:     &r_print($r,<<ENDUPDATE);
1.1041    www      9560: <script type="text/javascript">
                   9561: // <![CDATA[
1.1302    raeburn  9562: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9563: // ]]>
                   9564: </script>
                   9565: ENDUPDATE
1.1035    www      9566: }
                   9567: 
1.1042    www      9568: sub LCprogressbarClose {
                   9569:     my ($r)=@_;
                   9570:     $LClastpercent=0;
1.1044    www      9571:     &r_print($r,<<ENDCLOSE);
1.1042    www      9572: <script type="text/javascript">
                   9573: // <![CDATA[
1.1045    www      9574: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9575: // ]]>
                   9576: </script>
                   9577: ENDCLOSE
1.1044    www      9578: }
                   9579: 
                   9580: sub r_print {
                   9581:     my ($r,$to_print)=@_;
                   9582:     if ($r) {
                   9583:       $r->print($to_print);
                   9584:       $r->rflush();
                   9585:     } else {
                   9586:       print($to_print);
                   9587:     }
1.1042    www      9588: }
                   9589: 
1.320     albertel 9590: sub html_encode {
                   9591:     my ($result) = @_;
                   9592: 
1.322     albertel 9593:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9594:     
                   9595:     return $result;
                   9596: }
1.1044    www      9597: 
1.317     albertel 9598: sub js_ready {
                   9599:     my ($result) = @_;
                   9600: 
1.323     albertel 9601:     $result =~ s/[\n\r]/ /xmsg;
                   9602:     $result =~ s/\\/\\\\/xmsg;
                   9603:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9604:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9605:     
                   9606:     return $result;
                   9607: }
                   9608: 
1.315     albertel 9609: sub validate_page {
                   9610:     if (  exists($env{'internal.start_page'})
1.316     albertel 9611: 	  &&     $env{'internal.start_page'} > 1) {
                   9612: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9613: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9614: 				 $ENV{'request.filename'});
1.315     albertel 9615:     }
                   9616:     if (  exists($env{'internal.end_page'})
1.316     albertel 9617: 	  &&     $env{'internal.end_page'} > 1) {
                   9618: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9619: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9620: 				 $env{'request.filename'});
1.315     albertel 9621:     }
                   9622:     if (     exists($env{'internal.start_page'})
                   9623: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9624: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9625: 				 $env{'request.filename'});
1.315     albertel 9626:     }
                   9627:     if (   ! exists($env{'internal.start_page'})
                   9628: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9629: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9630: 				 $env{'request.filename'});
1.315     albertel 9631:     }
1.306     albertel 9632: }
1.315     albertel 9633: 
1.996     www      9634: 
                   9635: sub start_scrollbox {
1.1140    raeburn  9636:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9637:     unless ($outerwidth) { $outerwidth='520px'; }
                   9638:     unless ($width) { $width='500px'; }
                   9639:     unless ($height) { $height='200px'; }
1.1075    raeburn  9640:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9641:     if ($id ne '') {
1.1140    raeburn  9642:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9643:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9644:     }
1.1075    raeburn  9645:     if ($bgcolor ne '') {
                   9646:         $tdcol = "background-color: $bgcolor;";
                   9647:     }
1.1137    raeburn  9648:     my $nicescroll_js;
                   9649:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9650:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9651:     }
                   9652:     return <<"END";
                   9653: $nicescroll_js
                   9654: 
                   9655: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9656: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9657: END
                   9658: }
                   9659: 
                   9660: sub end_scrollbox {
                   9661:     return '</div></td></tr></table>';
                   9662: }
                   9663: 
                   9664: sub nicescroll_javascript {
                   9665:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9666:     my %options;
                   9667:     if (ref($cursor) eq 'HASH') {
                   9668:         %options = %{$cursor};
                   9669:     }
                   9670:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9671:         $options{'railalign'} = 'left';
                   9672:     }
                   9673:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9674:         my $function  = &get_users_function();
                   9675:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9676:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9677:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9678:         }
1.1140    raeburn  9679:     }
                   9680:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9681:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9682:             $options{'cursoropacity'}='1.0';
                   9683:         }
1.1140    raeburn  9684:     } else {
                   9685:         $options{'cursoropacity'}='1.0';
                   9686:     }
                   9687:     if ($options{'cursorfixedheight'} eq 'none') {
                   9688:         delete($options{'cursorfixedheight'});
                   9689:     } else {
                   9690:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9691:     }
                   9692:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9693:         delete($options{'railoffset'});
                   9694:     }
                   9695:     my @niceoptions;
                   9696:     while (my($key,$value) = each(%options)) {
                   9697:         if ($value =~ /^\{.+\}$/) {
                   9698:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9699:         } else {
1.1140    raeburn  9700:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9701:         }
1.1140    raeburn  9702:     }
                   9703:     my $nicescroll_js = '
1.1137    raeburn  9704: $(document).ready(
1.1140    raeburn  9705:       function() {
                   9706:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9707:       }
1.1137    raeburn  9708: );
                   9709: ';
1.1140    raeburn  9710:     if ($framecheck) {
                   9711:         $nicescroll_js .= '
                   9712: function expand_div(caller) {
                   9713:     if (top === self) {
                   9714:         document.getElementById("'.$id.'").style.width = "auto";
                   9715:         document.getElementById("'.$id.'").style.height = "auto";
                   9716:     } else {
                   9717:         try {
                   9718:             if (parent.frames) {
                   9719:                 if (parent.frames.length > 1) {
                   9720:                     var framesrc = parent.frames[1].location.href;
                   9721:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9722:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9723:                         document.getElementById("'.$id.'").style.width = "auto";
                   9724:                         document.getElementById("'.$id.'").style.height = "auto";
                   9725:                     }
                   9726:                 }
                   9727:             }
                   9728:         } catch (e) {
                   9729:             return;
                   9730:         }
1.1137    raeburn  9731:     }
1.1140    raeburn  9732:     return;
1.996     www      9733: }
1.1140    raeburn  9734: ';
                   9735:     }
                   9736:     if ($needjsready) {
                   9737:         $nicescroll_js = '
                   9738: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9739:     } else {
                   9740:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9741:     }
                   9742:     return $nicescroll_js;
1.996     www      9743: }
                   9744: 
1.318     albertel 9745: sub simple_error_page {
1.1150    bisitz   9746:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9747:     my %displayargs;
1.1151    raeburn  9748:     if (ref($args) eq 'HASH') {
                   9749:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9750:         if ($args->{'only_body'}) {
                   9751:             $displayargs{'only_body'} = 1;
                   9752:         }
                   9753:         if ($args->{'no_nav_bar'}) {
                   9754:             $displayargs{'no_nav_bar'} = 1;
                   9755:         }
1.1151    raeburn  9756:     } else {
                   9757:         $msg = &mt($msg);
                   9758:     }
1.1150    bisitz   9759: 
1.318     albertel 9760:     my $page =
1.1304    raeburn  9761: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9762: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9763: 	&Apache::loncommon::end_page();
                   9764:     if (ref($r)) {
                   9765: 	$r->print($page);
1.327     albertel 9766: 	return;
1.318     albertel 9767:     }
                   9768:     return $page;
                   9769: }
1.347     albertel 9770: 
                   9771: {
1.610     albertel 9772:     my @row_count;
1.961     onken    9773: 
                   9774:     sub start_data_table_count {
                   9775:         unshift(@row_count, 0);
                   9776:         return;
                   9777:     }
                   9778: 
                   9779:     sub end_data_table_count {
                   9780:         shift(@row_count);
                   9781:         return;
                   9782:     }
                   9783: 
1.347     albertel 9784:     sub start_data_table {
1.1018    raeburn  9785: 	my ($add_class,$id) = @_;
1.422     albertel 9786: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9787:         my $table_id;
                   9788:         if (defined($id)) {
                   9789:             $table_id = ' id="'.$id.'"';
                   9790:         }
1.961     onken    9791: 	&start_data_table_count();
1.1018    raeburn  9792: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9793:     }
                   9794: 
                   9795:     sub end_data_table {
1.961     onken    9796: 	&end_data_table_count();
1.389     albertel 9797: 	return '</table>'."\n";;
1.347     albertel 9798:     }
                   9799: 
                   9800:     sub start_data_table_row {
1.974     wenzelju 9801: 	my ($add_class, $id) = @_;
1.610     albertel 9802: 	$row_count[0]++;
                   9803: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9804: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9805:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9806:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9807:     }
1.471     banghart 9808:     
                   9809:     sub continue_data_table_row {
1.974     wenzelju 9810: 	my ($add_class, $id) = @_;
1.610     albertel 9811: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9812: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9813:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9814:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9815:     }
1.347     albertel 9816: 
                   9817:     sub end_data_table_row {
1.389     albertel 9818: 	return '</tr>'."\n";;
1.347     albertel 9819:     }
1.367     www      9820: 
1.421     albertel 9821:     sub start_data_table_empty_row {
1.707     bisitz   9822: #	$row_count[0]++;
1.421     albertel 9823: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9824:     }
                   9825: 
                   9826:     sub end_data_table_empty_row {
                   9827: 	return '</tr>'."\n";;
                   9828:     }
                   9829: 
1.367     www      9830:     sub start_data_table_header_row {
1.389     albertel 9831: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9832:     }
                   9833: 
                   9834:     sub end_data_table_header_row {
1.389     albertel 9835: 	return '</tr>'."\n";;
1.367     www      9836:     }
1.890     droeschl 9837: 
                   9838:     sub data_table_caption {
                   9839:         my $caption = shift;
                   9840:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9841:     }
1.347     albertel 9842: }
                   9843: 
1.548     albertel 9844: =pod
                   9845: 
                   9846: =item * &inhibit_menu_check($arg)
                   9847: 
                   9848: Checks for a inhibitmenu state and generates output to preserve it
                   9849: 
                   9850: Inputs:         $arg - can be any of
                   9851:                      - undef - in which case the return value is a string 
                   9852:                                to add  into arguments list of a uri
                   9853:                      - 'input' - in which case the return value is a HTML
                   9854:                                  <form> <input> field of type hidden to
                   9855:                                  preserve the value
                   9856:                      - a url - in which case the return value is the url with
                   9857:                                the neccesary cgi args added to preserve the
                   9858:                                inhibitmenu state
                   9859:                      - a ref to a url - no return value, but the string is
                   9860:                                         updated to include the neccessary cgi
                   9861:                                         args to preserve the inhibitmenu state
                   9862: 
                   9863: =cut
                   9864: 
                   9865: sub inhibit_menu_check {
                   9866:     my ($arg) = @_;
                   9867:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9868:     if ($arg eq 'input') {
                   9869: 	if ($env{'form.inhibitmenu'}) {
                   9870: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9871: 	} else {
                   9872: 	    return
                   9873: 	}
                   9874:     }
                   9875:     if ($env{'form.inhibitmenu'}) {
                   9876: 	if (ref($arg)) {
                   9877: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9878: 	} elsif ($arg eq '') {
                   9879: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9880: 	} else {
                   9881: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9882: 	}
                   9883:     }
                   9884:     if (!ref($arg)) {
                   9885: 	return $arg;
                   9886:     }
                   9887: }
                   9888: 
1.251     albertel 9889: ###############################################
1.182     matthew  9890: 
                   9891: =pod
                   9892: 
1.549     albertel 9893: =back
                   9894: 
                   9895: =head1 User Information Routines
                   9896: 
                   9897: =over 4
                   9898: 
1.405     albertel 9899: =item * &get_users_function()
1.182     matthew  9900: 
                   9901: Used by &bodytag to determine the current users primary role.
                   9902: Returns either 'student','coordinator','admin', or 'author'.
                   9903: 
                   9904: =cut
                   9905: 
                   9906: ###############################################
                   9907: sub get_users_function {
1.815     tempelho 9908:     my $function = 'norole';
1.818     tempelho 9909:     if ($env{'request.role'}=~/^(st)/) {
                   9910:         $function='student';
                   9911:     }
1.907     raeburn  9912:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9913:         $function='coordinator';
                   9914:     }
1.258     albertel 9915:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9916:         $function='admin';
                   9917:     }
1.826     bisitz   9918:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9919:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9920:         $function='author';
                   9921:     }
                   9922:     return $function;
1.54      www      9923: }
1.99      www      9924: 
                   9925: ###############################################
                   9926: 
1.233     raeburn  9927: =pod
                   9928: 
1.821     raeburn  9929: =item * &show_course()
                   9930: 
                   9931: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9932: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9933: 
                   9934: Inputs:
                   9935: None
                   9936: 
                   9937: Outputs:
                   9938: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9939: 
                   9940: =cut
                   9941: 
                   9942: ###############################################
                   9943: sub show_course {
                   9944:     my $course = !$env{'user.adv'};
                   9945:     if (!$env{'user.adv'}) {
                   9946:         foreach my $env (keys(%env)) {
                   9947:             next if ($env !~ m/^user\.priv\./);
                   9948:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9949:                 $course = 0;
                   9950:                 last;
                   9951:             }
                   9952:         }
                   9953:     }
                   9954:     return $course;
                   9955: }
                   9956: 
                   9957: ###############################################
                   9958: 
                   9959: =pod
                   9960: 
1.542     raeburn  9961: =item * &check_user_status()
1.274     raeburn  9962: 
                   9963: Determines current status of supplied role for a
                   9964: specific user. Roles can be active, previous or future.
                   9965: 
                   9966: Inputs: 
                   9967: user's domain, user's username, course's domain,
1.375     raeburn  9968: course's number, optional section ID.
1.274     raeburn  9969: 
                   9970: Outputs:
                   9971: role status: active, previous or future. 
                   9972: 
                   9973: =cut
                   9974: 
                   9975: sub check_user_status {
1.412     raeburn  9976:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9977:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9978:     my @uroles = keys(%userinfo);
1.274     raeburn  9979:     my $srchstr;
                   9980:     my $active_chk = 'none';
1.412     raeburn  9981:     my $now = time;
1.274     raeburn  9982:     if (@uroles > 0) {
1.908     raeburn  9983:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9984:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9985:         } else {
1.412     raeburn  9986:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9987:         }
                   9988:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9989:             my $role_end = 0;
                   9990:             my $role_start = 0;
                   9991:             $active_chk = 'active';
1.412     raeburn  9992:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9993:                 $role_end = $1;
                   9994:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9995:                     $role_start = $1;
1.274     raeburn  9996:                 }
                   9997:             }
                   9998:             if ($role_start > 0) {
1.412     raeburn  9999:                 if ($now < $role_start) {
1.274     raeburn  10000:                     $active_chk = 'future';
                   10001:                 }
                   10002:             }
                   10003:             if ($role_end > 0) {
1.412     raeburn  10004:                 if ($now > $role_end) {
1.274     raeburn  10005:                     $active_chk = 'previous';
                   10006:                 }
                   10007:             }
                   10008:         }
                   10009:     }
                   10010:     return $active_chk;
                   10011: }
                   10012: 
                   10013: ###############################################
                   10014: 
                   10015: =pod
                   10016: 
1.405     albertel 10017: =item * &get_sections()
1.233     raeburn  10018: 
                   10019: Determines all the sections for a course including
                   10020: sections with students and sections containing other roles.
1.419     raeburn  10021: Incoming parameters: 
                   10022: 
                   10023: 1. domain
                   10024: 2. course number 
                   10025: 3. reference to array containing roles for which sections should 
                   10026: be gathered (optional).
                   10027: 4. reference to array containing status types for which sections 
                   10028: should be gathered (optional).
                   10029: 
                   10030: If the third argument is undefined, sections are gathered for any role. 
                   10031: If the fourth argument is undefined, sections are gathered for any status.
                   10032: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10033:  
1.374     raeburn  10034: Returns section hash (keys are section IDs, values are
                   10035: number of users in each section), subject to the
1.419     raeburn  10036: optional roles filter, optional status filter 
1.233     raeburn  10037: 
                   10038: =cut
                   10039: 
                   10040: ###############################################
                   10041: sub get_sections {
1.419     raeburn  10042:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10043:     if (!defined($cdom) || !defined($cnum)) {
                   10044:         my $cid =  $env{'request.course.id'};
                   10045: 
                   10046: 	return if (!defined($cid));
                   10047: 
                   10048:         $cdom = $env{'course.'.$cid.'.domain'};
                   10049:         $cnum = $env{'course.'.$cid.'.num'};
                   10050:     }
                   10051: 
                   10052:     my %sectioncount;
1.419     raeburn  10053:     my $now = time;
1.240     albertel 10054: 
1.1118    raeburn  10055:     my $check_students = 1;
                   10056:     my $only_students = 0;
                   10057:     if (ref($possible_roles) eq 'ARRAY') {
                   10058:         if (grep(/^st$/,@{$possible_roles})) {
                   10059:             if (@{$possible_roles} == 1) {
                   10060:                 $only_students = 1;
                   10061:             }
                   10062:         } else {
                   10063:             $check_students = 0;
                   10064:         }
                   10065:     }
                   10066: 
                   10067:     if ($check_students) { 
1.276     albertel 10068: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10069: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10070: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10071:         my $start_index = &Apache::loncoursedata::CL_START();
                   10072:         my $end_index = &Apache::loncoursedata::CL_END();
                   10073:         my $status;
1.366     albertel 10074: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10075: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10076: 				                     $data->[$status_index],
                   10077:                                                      $data->[$start_index],
                   10078:                                                      $data->[$end_index]);
                   10079:             if ($stu_status eq 'Active') {
                   10080:                 $status = 'active';
                   10081:             } elsif ($end < $now) {
                   10082:                 $status = 'previous';
                   10083:             } elsif ($start > $now) {
                   10084:                 $status = 'future';
                   10085:             } 
                   10086: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10087:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10088:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10089: 		    $sectioncount{$section}++;
                   10090:                 }
1.240     albertel 10091: 	    }
                   10092: 	}
                   10093:     }
1.1118    raeburn  10094:     if ($only_students) {
                   10095:         return %sectioncount;
                   10096:     }
1.240     albertel 10097:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10098:     foreach my $user (sort(keys(%courseroles))) {
                   10099: 	if ($user !~ /^(\w{2})/) { next; }
                   10100: 	my ($role) = ($user =~ /^(\w{2})/);
                   10101: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10102: 	my ($section,$status);
1.240     albertel 10103: 	if ($role eq 'cr' &&
                   10104: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10105: 	    $section=$1;
                   10106: 	}
                   10107: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10108: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10109:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10110:         if ($end == -1 && $start == -1) {
                   10111:             next; #deleted role
                   10112:         }
                   10113:         if (!defined($possible_status)) { 
                   10114:             $sectioncount{$section}++;
                   10115:         } else {
                   10116:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10117:                 $status = 'active';
                   10118:             } elsif ($end < $now) {
                   10119:                 $status = 'future';
                   10120:             } elsif ($start > $now) {
                   10121:                 $status = 'previous';
                   10122:             }
                   10123:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10124:                 $sectioncount{$section}++;
                   10125:             }
                   10126:         }
1.233     raeburn  10127:     }
1.366     albertel 10128:     return %sectioncount;
1.233     raeburn  10129: }
                   10130: 
1.274     raeburn  10131: ###############################################
1.294     raeburn  10132: 
                   10133: =pod
1.405     albertel 10134: 
                   10135: =item * &get_course_users()
                   10136: 
1.275     raeburn  10137: Retrieves usernames:domains for users in the specified course
                   10138: with specific role(s), and access status. 
                   10139: 
                   10140: Incoming parameters:
1.277     albertel 10141: 1. course domain
                   10142: 2. course number
                   10143: 3. access status: users must have - either active, 
1.275     raeburn  10144: previous, future, or all.
1.277     albertel 10145: 4. reference to array of permissible roles
1.288     raeburn  10146: 5. reference to array of section restrictions (optional)
                   10147: 6. reference to results object (hash of hashes).
                   10148: 7. reference to optional userdata hash
1.609     raeburn  10149: 8. reference to optional statushash
1.630     raeburn  10150: 9. flag if privileged users (except those set to unhide in
                   10151:    course settings) should be excluded    
1.609     raeburn  10152: Keys of top level results hash are roles.
1.275     raeburn  10153: Keys of inner hashes are username:domain, with 
                   10154: values set to access type.
1.288     raeburn  10155: Optional userdata hash returns an array with arguments in the 
                   10156: same order as loncoursedata::get_classlist() for student data.
                   10157: 
1.609     raeburn  10158: Optional statushash returns
                   10159: 
1.288     raeburn  10160: Entries for end, start, section and status are blank because
                   10161: of the possibility of multiple values for non-student roles.
                   10162: 
1.275     raeburn  10163: =cut
1.405     albertel 10164: 
1.275     raeburn  10165: ###############################################
1.405     albertel 10166: 
1.275     raeburn  10167: sub get_course_users {
1.630     raeburn  10168:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10169:     my %idx = ();
1.419     raeburn  10170:     my %seclists;
1.288     raeburn  10171: 
                   10172:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10173:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10174:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10175:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10176:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10177:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10178:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10179:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10180: 
1.290     albertel 10181:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10182:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10183:         my $now = time;
1.277     albertel 10184:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10185:             my $match = 0;
1.412     raeburn  10186:             my $secmatch = 0;
1.419     raeburn  10187:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10188:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10189:             if ($section eq '') {
                   10190:                 $section = 'none';
                   10191:             }
1.291     albertel 10192:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10193:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10194:                     $secmatch = 1;
                   10195:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10196:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10197:                         $secmatch = 1;
                   10198:                     }
                   10199:                 } else {  
1.419     raeburn  10200: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10201: 		        $secmatch = 1;
                   10202:                     }
1.290     albertel 10203: 		}
1.412     raeburn  10204:                 if (!$secmatch) {
                   10205:                     next;
                   10206:                 }
1.419     raeburn  10207:             }
1.275     raeburn  10208:             if (defined($$types{'active'})) {
1.288     raeburn  10209:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10210:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10211:                     $match = 1;
1.275     raeburn  10212:                 }
                   10213:             }
                   10214:             if (defined($$types{'previous'})) {
1.609     raeburn  10215:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10216:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10217:                     $match = 1;
1.275     raeburn  10218:                 }
                   10219:             }
                   10220:             if (defined($$types{'future'})) {
1.609     raeburn  10221:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10222:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10223:                     $match = 1;
1.275     raeburn  10224:                 }
                   10225:             }
1.609     raeburn  10226:             if ($match) {
                   10227:                 push(@{$seclists{$student}},$section);
                   10228:                 if (ref($userdata) eq 'HASH') {
                   10229:                     $$userdata{$student} = $$classlist{$student};
                   10230:                 }
                   10231:                 if (ref($statushash) eq 'HASH') {
                   10232:                     $statushash->{$student}{'st'}{$section} = $status;
                   10233:                 }
1.288     raeburn  10234:             }
1.275     raeburn  10235:         }
                   10236:     }
1.412     raeburn  10237:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10238:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10239:         my $now = time;
1.609     raeburn  10240:         my %displaystatus = ( previous => 'Expired',
                   10241:                               active   => 'Active',
                   10242:                               future   => 'Future',
                   10243:                             );
1.1121    raeburn  10244:         my (%nothide,@possdoms);
1.630     raeburn  10245:         if ($hidepriv) {
                   10246:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10247:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10248:                 if ($user !~ /:/) {
                   10249:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10250:                 } else {
                   10251:                     $nothide{$user} = 1;
                   10252:                 }
                   10253:             }
1.1121    raeburn  10254:             my @possdoms = ($cdom);
                   10255:             if ($coursehash{'checkforpriv'}) {
                   10256:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10257:             }
1.630     raeburn  10258:         }
1.439     raeburn  10259:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10260:             my $match = 0;
1.412     raeburn  10261:             my $secmatch = 0;
1.439     raeburn  10262:             my $status;
1.412     raeburn  10263:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10264:             $user =~ s/:$//;
1.439     raeburn  10265:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10266:             if ($end == -1 || $start == -1) {
                   10267:                 next;
                   10268:             }
                   10269:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10270:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10271:                 my ($uname,$udom) = split(/:/,$user);
                   10272:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10273:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10274:                         $secmatch = 1;
                   10275:                     } elsif ($usec eq '') {
1.420     albertel 10276:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10277:                             $secmatch = 1;
                   10278:                         }
                   10279:                     } else {
                   10280:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10281:                             $secmatch = 1;
                   10282:                         }
                   10283:                     }
                   10284:                     if (!$secmatch) {
                   10285:                         next;
                   10286:                     }
1.288     raeburn  10287:                 }
1.419     raeburn  10288:                 if ($usec eq '') {
                   10289:                     $usec = 'none';
                   10290:                 }
1.275     raeburn  10291:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10292:                     if ($hidepriv) {
1.1121    raeburn  10293:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10294:                             (!$nothide{$uname.':'.$udom})) {
                   10295:                             next;
                   10296:                         }
                   10297:                     }
1.503     raeburn  10298:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10299:                         $status = 'previous';
                   10300:                     } elsif ($start > $now) {
                   10301:                         $status = 'future';
                   10302:                     } else {
                   10303:                         $status = 'active';
                   10304:                     }
1.277     albertel 10305:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10306:                         if ($status eq $type) {
1.420     albertel 10307:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10308:                                 push(@{$$users{$role}{$user}},$type);
                   10309:                             }
1.288     raeburn  10310:                             $match = 1;
                   10311:                         }
                   10312:                     }
1.419     raeburn  10313:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10314:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10315: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10316:                         }
1.420     albertel 10317:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10318:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10319:                         }
1.609     raeburn  10320:                         if (ref($statushash) eq 'HASH') {
                   10321:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10322:                         }
1.275     raeburn  10323:                     }
                   10324:                 }
                   10325:             }
                   10326:         }
1.290     albertel 10327:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10328:             if ((defined($cdom)) && (defined($cnum))) {
                   10329:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10330:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10331:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10332:                     next if ($owner eq '');
                   10333:                     my ($ownername,$ownerdom);
                   10334:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10335:                         $ownername = $1;
                   10336:                         $ownerdom = $2;
                   10337:                     } else {
                   10338:                         $ownername = $owner;
                   10339:                         $ownerdom = $cdom;
                   10340:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10341:                     }
                   10342:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10343:                     if (defined($userdata) && 
1.609     raeburn  10344: 			!exists($$userdata{$owner})) {
                   10345: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10346:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10347:                             push(@{$seclists{$owner}},'none');
                   10348:                         }
                   10349:                         if (ref($statushash) eq 'HASH') {
                   10350:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10351:                         }
1.290     albertel 10352: 		    }
1.279     raeburn  10353:                 }
                   10354:             }
                   10355:         }
1.419     raeburn  10356:         foreach my $user (keys(%seclists)) {
                   10357:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10358:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10359:         }
1.275     raeburn  10360:     }
                   10361:     return;
                   10362: }
                   10363: 
1.288     raeburn  10364: sub get_user_info {
                   10365:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10366:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10367: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10368:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10369:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10370:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10371:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10372:     return;
                   10373: }
1.275     raeburn  10374: 
1.472     raeburn  10375: ###############################################
                   10376: 
                   10377: =pod
                   10378: 
                   10379: =item * &get_user_quota()
                   10380: 
1.1134    raeburn  10381: Retrieves quota assigned for storage of user files.
                   10382: Default is to report quota for portfolio files.
1.472     raeburn  10383: 
                   10384: Incoming parameters:
                   10385: 1. user's username
                   10386: 2. user's domain
1.1134    raeburn  10387: 3. quota name - portfolio, author, or course
1.1136    raeburn  10388:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10389: 4. crstype - official, unofficial, textbook, placement or community, 
                   10390:    if quota name is course
1.472     raeburn  10391: 
                   10392: Returns:
1.1163    raeburn  10393: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10394: 2. (Optional) Type of setting: custom or default
                   10395:    (individually assigned or default for user's 
                   10396:    institutional status).
                   10397: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10398:    or student - types as defined in localenroll::inst_usertypes 
                   10399:    for user's domain, which determines default quota for user.
                   10400: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10401: 
                   10402: If a value has been stored in the user's environment, 
1.536     raeburn  10403: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10404: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10405: 
                   10406: =cut
                   10407: 
                   10408: ###############################################
                   10409: 
                   10410: 
                   10411: sub get_user_quota {
1.1136    raeburn  10412:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10413:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10414:     if (!defined($udom)) {
                   10415:         $udom = $env{'user.domain'};
                   10416:     }
                   10417:     if (!defined($uname)) {
                   10418:         $uname = $env{'user.name'};
                   10419:     }
                   10420:     if (($udom eq '' || $uname eq '') ||
                   10421:         ($udom eq 'public') && ($uname eq 'public')) {
                   10422:         $quota = 0;
1.536     raeburn  10423:         $quotatype = 'default';
                   10424:         $defquota = 0; 
1.472     raeburn  10425:     } else {
1.536     raeburn  10426:         my $inststatus;
1.1134    raeburn  10427:         if ($quotaname eq 'course') {
                   10428:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10429:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10430:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10431:             } else {
                   10432:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10433:                 $quota = $cenv{'internal.uploadquota'};
                   10434:             }
1.536     raeburn  10435:         } else {
1.1134    raeburn  10436:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10437:                 if ($quotaname eq 'author') {
                   10438:                     $quota = $env{'environment.authorquota'};
                   10439:                 } else {
                   10440:                     $quota = $env{'environment.portfolioquota'};
                   10441:                 }
                   10442:                 $inststatus = $env{'environment.inststatus'};
                   10443:             } else {
                   10444:                 my %userenv = 
                   10445:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10446:                                          'authorquota','inststatus'],$udom,$uname);
                   10447:                 my ($tmp) = keys(%userenv);
                   10448:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10449:                     if ($quotaname eq 'author') {
                   10450:                         $quota = $userenv{'authorquota'};
                   10451:                     } else {
                   10452:                         $quota = $userenv{'portfolioquota'};
                   10453:                     }
                   10454:                     $inststatus = $userenv{'inststatus'};
                   10455:                 } else {
                   10456:                     undef(%userenv);
                   10457:                 }
                   10458:             }
                   10459:         }
                   10460:         if ($quota eq '' || wantarray) {
                   10461:             if ($quotaname eq 'course') {
                   10462:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10463:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10464:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10465:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10466:                     $defquota = $domdefs{$crstype.'quota'};
                   10467:                 }
                   10468:                 if ($defquota eq '') {
                   10469:                     $defquota = 500;
                   10470:                 }
1.1134    raeburn  10471:             } else {
                   10472:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10473:             }
                   10474:             if ($quota eq '') {
                   10475:                 $quota = $defquota;
                   10476:                 $quotatype = 'default';
                   10477:             } else {
                   10478:                 $quotatype = 'custom';
                   10479:             }
1.472     raeburn  10480:         }
                   10481:     }
1.536     raeburn  10482:     if (wantarray) {
                   10483:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10484:     } else {
                   10485:         return $quota;
                   10486:     }
1.472     raeburn  10487: }
                   10488: 
                   10489: ###############################################
                   10490: 
                   10491: =pod
                   10492: 
                   10493: =item * &default_quota()
                   10494: 
1.536     raeburn  10495: Retrieves default quota assigned for storage of user portfolio files,
                   10496: given an (optional) user's institutional status.
1.472     raeburn  10497: 
                   10498: Incoming parameters:
1.1142    raeburn  10499: 
1.472     raeburn  10500: 1. domain
1.536     raeburn  10501: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10502:    status types (e.g., faculty, staff, student etc.)
                   10503:    which apply to the user for whom the default is being retrieved.
                   10504:    If the institutional status string in undefined, the domain
1.1134    raeburn  10505:    default quota will be returned.
                   10506: 3.  quota name - portfolio, author, or course
                   10507:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10508: 
                   10509: Returns:
1.1142    raeburn  10510: 
1.1163    raeburn  10511: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10512: 2. (Optional) institutional type which determined the value of the
                   10513:    default quota.
1.472     raeburn  10514: 
                   10515: If a value has been stored in the domain's configuration db,
                   10516: it will return that, otherwise it returns 20 (for backwards 
                   10517: compatibility with domains which have not set up a configuration
1.1163    raeburn  10518: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10519: 
1.536     raeburn  10520: If the user's status includes multiple types (e.g., staff and student),
                   10521: the largest default quota which applies to the user determines the
                   10522: default quota returned.
                   10523: 
1.472     raeburn  10524: =cut
                   10525: 
                   10526: ###############################################
                   10527: 
                   10528: 
                   10529: sub default_quota {
1.1134    raeburn  10530:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10531:     my ($defquota,$settingstatus);
                   10532:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10533:                                             ['quotas'],$udom);
1.1134    raeburn  10534:     my $key = 'defaultquota';
                   10535:     if ($quotaname eq 'author') {
                   10536:         $key = 'authorquota';
                   10537:     }
1.622     raeburn  10538:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10539:         if ($inststatus ne '') {
1.765     raeburn  10540:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10541:             foreach my $item (@statuses) {
1.1134    raeburn  10542:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10543:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10544:                         if ($defquota eq '') {
1.1134    raeburn  10545:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10546:                             $settingstatus = $item;
1.1134    raeburn  10547:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10548:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10549:                             $settingstatus = $item;
                   10550:                         }
                   10551:                     }
1.1134    raeburn  10552:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10553:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10554:                         if ($defquota eq '') {
                   10555:                             $defquota = $quotahash{'quotas'}{$item};
                   10556:                             $settingstatus = $item;
                   10557:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10558:                             $defquota = $quotahash{'quotas'}{$item};
                   10559:                             $settingstatus = $item;
                   10560:                         }
1.536     raeburn  10561:                     }
                   10562:                 }
                   10563:             }
                   10564:         }
                   10565:         if ($defquota eq '') {
1.1134    raeburn  10566:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10567:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10568:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10569:                 $defquota = $quotahash{'quotas'}{'default'};
                   10570:             }
1.536     raeburn  10571:             $settingstatus = 'default';
1.1139    raeburn  10572:             if ($defquota eq '') {
                   10573:                 if ($quotaname eq 'author') {
                   10574:                     $defquota = 500;
                   10575:                 }
                   10576:             }
1.536     raeburn  10577:         }
                   10578:     } else {
                   10579:         $settingstatus = 'default';
1.1134    raeburn  10580:         if ($quotaname eq 'author') {
                   10581:             $defquota = 500;
                   10582:         } else {
                   10583:             $defquota = 20;
                   10584:         }
1.536     raeburn  10585:     }
                   10586:     if (wantarray) {
                   10587:         return ($defquota,$settingstatus);
1.472     raeburn  10588:     } else {
1.536     raeburn  10589:         return $defquota;
1.472     raeburn  10590:     }
                   10591: }
                   10592: 
1.1135    raeburn  10593: ###############################################
                   10594: 
                   10595: =pod
                   10596: 
1.1136    raeburn  10597: =item * &excess_filesize_warning()
1.1135    raeburn  10598: 
                   10599: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10600: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10601: space to be exceeded.
1.1136    raeburn  10602: 
                   10603: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10604: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10605: 
1.1165    raeburn  10606: Inputs: 7 
1.1136    raeburn  10607: 1. username or coursenum
1.1135    raeburn  10608: 2. domain
1.1136    raeburn  10609: 3. context ('author' or 'course')
1.1135    raeburn  10610: 4. filename of file for which action is being requested
                   10611: 5. filesize (kB) of file
                   10612: 6. action being taken: copy or upload.
1.1237    raeburn  10613: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10614: 
                   10615: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10616:          otherwise return null.
                   10617: 
                   10618: =back
1.1135    raeburn  10619: 
                   10620: =cut
                   10621: 
1.1136    raeburn  10622: sub excess_filesize_warning {
1.1165    raeburn  10623:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10624:     my $current_disk_usage = 0;
1.1165    raeburn  10625:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10626:     if ($context eq 'author') {
                   10627:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10628:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10629:     } else {
                   10630:         foreach my $subdir ('docs','supplemental') {
                   10631:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10632:         }
                   10633:     }
1.1135    raeburn  10634:     $disk_quota = int($disk_quota * 1000);
                   10635:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10636:         return '<p class="LC_warning">'.
1.1135    raeburn  10637:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10638:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10639:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10640:                             $disk_quota,$current_disk_usage).
                   10641:                '</p>';
                   10642:     }
                   10643:     return;
                   10644: }
                   10645: 
                   10646: ###############################################
                   10647: 
                   10648: 
1.1136    raeburn  10649: 
                   10650: 
1.384     raeburn  10651: sub get_secgrprole_info {
                   10652:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10653:     my %sections_count = &get_sections($cdom,$cnum);
                   10654:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10655:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10656:     my @groups = sort(keys(%curr_groups));
                   10657:     my $allroles = [];
                   10658:     my $rolehash;
                   10659:     my $accesshash = {
                   10660:                      active => 'Currently has access',
                   10661:                      future => 'Will have future access',
                   10662:                      previous => 'Previously had access',
                   10663:                   };
                   10664:     if ($needroles) {
                   10665:         $rolehash = {'all' => 'all'};
1.385     albertel 10666:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10667: 	if (&Apache::lonnet::error(%user_roles)) {
                   10668: 	    undef(%user_roles);
                   10669: 	}
                   10670:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10671:             my ($role)=split(/\:/,$item,2);
                   10672:             if ($role eq 'cr') { next; }
                   10673:             if ($role =~ /^cr/) {
                   10674:                 $$rolehash{$role} = (split('/',$role))[3];
                   10675:             } else {
                   10676:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10677:             }
                   10678:         }
                   10679:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10680:             push(@{$allroles},$key);
                   10681:         }
                   10682:         push (@{$allroles},'st');
                   10683:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10684:     }
                   10685:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10686: }
                   10687: 
1.555     raeburn  10688: sub user_picker {
1.1279    raeburn  10689:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10690:     my $currdom = $dom;
1.1253    raeburn  10691:     my @alldoms = &Apache::lonnet::all_domains();
                   10692:     if (@alldoms == 1) {
                   10693:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10694:                                                ['directorysrch'],$alldoms[0]);
                   10695:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10696:         my $showdom = $domdesc;
                   10697:         if ($showdom eq '') {
                   10698:             $showdom = $dom;
                   10699:         }
                   10700:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10701:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10702:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10703:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10704:             }
                   10705:         }
                   10706:     }
1.555     raeburn  10707:     my %curr_selected = (
                   10708:                         srchin => 'dom',
1.580     raeburn  10709:                         srchby => 'lastname',
1.555     raeburn  10710:                       );
                   10711:     my $srchterm;
1.625     raeburn  10712:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10713:         if ($srch->{'srchby'} ne '') {
                   10714:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10715:         }
                   10716:         if ($srch->{'srchin'} ne '') {
                   10717:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10718:         }
                   10719:         if ($srch->{'srchtype'} ne '') {
                   10720:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10721:         }
                   10722:         if ($srch->{'srchdomain'} ne '') {
                   10723:             $currdom = $srch->{'srchdomain'};
                   10724:         }
                   10725:         $srchterm = $srch->{'srchterm'};
                   10726:     }
1.1222    damieng  10727:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10728:                     'usr'       => 'Search criteria',
1.563     raeburn  10729:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10730:                     'uname'     => 'username',
                   10731:                     'lastname'  => 'last name',
1.555     raeburn  10732:                     'lastfirst' => 'last name, first name',
1.558     albertel 10733:                     'crs'       => 'in this course',
1.576     raeburn  10734:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10735:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10736:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10737:                     'exact'     => 'is',
                   10738:                     'contains'  => 'contains',
1.569     raeburn  10739:                     'begins'    => 'begins with',
1.1222    damieng  10740:                                        );
                   10741:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10742:                     'youm'      => "You must include some text to search for.",
                   10743:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10744:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10745:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10746:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10747:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10748:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10749:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10750:                                        );
1.1222    damieng  10751:     &html_escape(\%html_lt);
                   10752:     &js_escape(\%js_lt);
1.1255    raeburn  10753:     my $domform;
1.1277    raeburn  10754:     my $allow_blank = 1;
1.1255    raeburn  10755:     if ($fixeddom) {
1.1277    raeburn  10756:         $allow_blank = 0;
                   10757:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10758:     } else {
1.1287    raeburn  10759:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10760:         my ($trusted,$untrusted);
1.1287    raeburn  10761:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10762:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10763:         } elsif ($context eq 'author') {
1.1288    raeburn  10764:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10765:         } elsif ($context eq 'domain') {
1.1288    raeburn  10766:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10767:         }
1.1288    raeburn  10768:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10769:     }
1.563     raeburn  10770:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10771: 
                   10772:     my @srchins = ('crs','dom','alc','instd');
                   10773: 
                   10774:     foreach my $option (@srchins) {
                   10775:         # FIXME 'alc' option unavailable until 
                   10776:         #       loncreateuser::print_user_query_page()
                   10777:         #       has been completed.
                   10778:         next if ($option eq 'alc');
1.880     raeburn  10779:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10780:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10781:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10782:         if ($curr_selected{'srchin'} eq $option) {
                   10783:             $srchinsel .= ' 
1.1222    damieng  10784:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10785:         } else {
                   10786:             $srchinsel .= '
1.1222    damieng  10787:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10788:         }
1.555     raeburn  10789:     }
1.563     raeburn  10790:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10791: 
                   10792:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10793:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10794:         if ($curr_selected{'srchby'} eq $option) {
                   10795:             $srchbysel .= '
1.1222    damieng  10796:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10797:         } else {
                   10798:             $srchbysel .= '
1.1222    damieng  10799:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10800:          }
                   10801:     }
                   10802:     $srchbysel .= "\n  </select>\n";
                   10803: 
                   10804:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10805:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10806:         if ($curr_selected{'srchtype'} eq $option) {
                   10807:             $srchtypesel .= '
1.1222    damieng  10808:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10809:         } else {
                   10810:             $srchtypesel .= '
1.1222    damieng  10811:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10812:         }
                   10813:     }
                   10814:     $srchtypesel .= "\n  </select>\n";
                   10815: 
1.558     albertel 10816:     my ($newuserscript,$new_user_create);
1.994     raeburn  10817:     my $context_dom = $env{'request.role.domain'};
                   10818:     if ($context eq 'requestcrs') {
                   10819:         if ($env{'form.coursedom'} ne '') { 
                   10820:             $context_dom = $env{'form.coursedom'};
                   10821:         }
                   10822:     }
1.556     raeburn  10823:     if ($forcenewuser) {
1.576     raeburn  10824:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10825:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10826:                 if ($cancreate) {
                   10827:                     $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>';
                   10828:                 } else {
1.799     bisitz   10829:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10830:                     my %usertypetext = (
                   10831:                         official   => 'institutional',
                   10832:                         unofficial => 'non-institutional',
                   10833:                     );
1.799     bisitz   10834:                     $new_user_create = '<p class="LC_warning">'
                   10835:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10836:                                       .' '
                   10837:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10838:                                           ,'<a href="'.$helplink.'">','</a>')
                   10839:                                       .'</p><br />';
1.627     raeburn  10840:                 }
1.576     raeburn  10841:             }
                   10842:         }
                   10843: 
1.556     raeburn  10844:         $newuserscript = <<"ENDSCRIPT";
                   10845: 
1.570     raeburn  10846: function setSearch(createnew,callingForm) {
1.556     raeburn  10847:     if (createnew == 1) {
1.570     raeburn  10848:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10849:             if (callingForm.srchby.options[i].value == 'uname') {
                   10850:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10851:             }
                   10852:         }
1.570     raeburn  10853:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10854:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10855: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10856:             }
                   10857:         }
1.570     raeburn  10858:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10859:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10860:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10861:             }
                   10862:         }
1.570     raeburn  10863:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10864:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10865:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10866:             }
                   10867:         }
                   10868:     }
                   10869: }
                   10870: ENDSCRIPT
1.558     albertel 10871: 
1.556     raeburn  10872:     }
                   10873: 
1.555     raeburn  10874:     my $output = <<"END_BLOCK";
1.556     raeburn  10875: <script type="text/javascript">
1.824     bisitz   10876: // <![CDATA[
1.570     raeburn  10877: function validateEntry(callingForm) {
1.558     albertel 10878: 
1.556     raeburn  10879:     var checkok = 1;
1.558     albertel 10880:     var srchin;
1.570     raeburn  10881:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10882: 	if ( callingForm.srchin[i].checked ) {
                   10883: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10884: 	}
                   10885:     }
                   10886: 
1.570     raeburn  10887:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10888:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10889:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10890:     var srchterm =  callingForm.srchterm.value;
                   10891:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10892:     var msg = "";
                   10893: 
                   10894:     if (srchterm == "") {
                   10895:         checkok = 0;
1.1222    damieng  10896:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10897:     }
                   10898: 
1.569     raeburn  10899:     if (srchtype== 'begins') {
                   10900:         if (srchterm.length < 2) {
                   10901:             checkok = 0;
1.1222    damieng  10902:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10903:         }
                   10904:     }
                   10905: 
1.556     raeburn  10906:     if (srchtype== 'contains') {
                   10907:         if (srchterm.length < 3) {
                   10908:             checkok = 0;
1.1222    damieng  10909:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10910:         }
                   10911:     }
                   10912:     if (srchin == 'instd') {
                   10913:         if (srchdomain == '') {
                   10914:             checkok = 0;
1.1222    damieng  10915:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10916:         }
                   10917:     }
                   10918:     if (srchin == 'dom') {
                   10919:         if (srchdomain == '') {
                   10920:             checkok = 0;
1.1222    damieng  10921:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10922:         }
                   10923:     }
                   10924:     if (srchby == 'lastfirst') {
                   10925:         if (srchterm.indexOf(",") == -1) {
                   10926:             checkok = 0;
1.1222    damieng  10927:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10928:         }
                   10929:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10930:             checkok = 0;
1.1222    damieng  10931:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10932:         }
                   10933:     }
                   10934:     if (checkok == 0) {
1.1222    damieng  10935:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10936:         return;
                   10937:     }
                   10938:     if (checkok == 1) {
1.570     raeburn  10939:         callingForm.submit();
1.556     raeburn  10940:     }
                   10941: }
                   10942: 
                   10943: $newuserscript
                   10944: 
1.824     bisitz   10945: // ]]>
1.556     raeburn  10946: </script>
1.558     albertel 10947: 
                   10948: $new_user_create
                   10949: 
1.555     raeburn  10950: END_BLOCK
1.558     albertel 10951: 
1.876     raeburn  10952:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10953:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10954:                $domform.
                   10955:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10956:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10957:                $srchbysel.
                   10958:                $srchtypesel. 
                   10959:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10960:                $srchinsel.
                   10961:                &Apache::lonhtmlcommon::row_closure(1). 
                   10962:                &Apache::lonhtmlcommon::end_pick_box().
                   10963:                '<br />';
1.1253    raeburn  10964:     return ($output,1);
1.555     raeburn  10965: }
                   10966: 
1.612     raeburn  10967: sub user_rule_check {
1.615     raeburn  10968:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10969:     my ($response,%inst_response);
1.612     raeburn  10970:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10971:         if (keys(%{$usershash}) > 1) {
                   10972:             my (%by_username,%by_id,%userdoms);
                   10973:             my $checkid; 
                   10974:             if (ref($checks) eq 'HASH') {
                   10975:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10976:                     $checkid = 1;
                   10977:                 }
                   10978:             }
                   10979:             foreach my $user (keys(%{$usershash})) {
                   10980:                 my ($uname,$udom) = split(/:/,$user);
                   10981:                 if ($checkid) {
                   10982:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10983:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10984:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10985:                             $userdoms{$udom} = 1;
1.1227    raeburn  10986:                             if (ref($inst_results) eq 'HASH') {
                   10987:                                 $inst_results->{$uname.':'.$udom} = {};
                   10988:                             }
1.1226    raeburn  10989:                         }
                   10990:                     }
                   10991:                 } else {
                   10992:                     $by_username{$udom}{$uname} = 1;
                   10993:                     $userdoms{$udom} = 1;
1.1227    raeburn  10994:                     if (ref($inst_results) eq 'HASH') {
                   10995:                         $inst_results->{$uname.':'.$udom} = {};
                   10996:                     }
1.1226    raeburn  10997:                 }
                   10998:             }
                   10999:             foreach my $udom (keys(%userdoms)) {
                   11000:                 if (!$got_rules->{$udom}) {
                   11001:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11002:                                                              ['usercreation'],$udom);
                   11003:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11004:                         foreach my $item ('username','id') {
                   11005:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11006:                                 $$curr_rules{$udom}{$item} =
                   11007:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11008:                             }
                   11009:                         }
                   11010:                     }
                   11011:                     $got_rules->{$udom} = 1;
                   11012:                 }
1.612     raeburn  11013:             }
1.1226    raeburn  11014:             if ($checkid) {
                   11015:                 foreach my $udom (keys(%by_id)) {
                   11016:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11017:                     if ($outcome eq 'ok') {
1.1227    raeburn  11018:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11019:                             my $uname = $by_id{$udom}{$id};
                   11020:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11021:                         }
1.1226    raeburn  11022:                         if (ref($results) eq 'HASH') {
                   11023:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11024:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11025:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11026:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11027:                                 }
1.1226    raeburn  11028:                             }
                   11029:                         }
                   11030:                     }
1.612     raeburn  11031:                 }
1.615     raeburn  11032:             } else {
1.1226    raeburn  11033:                 foreach my $udom (keys(%by_username)) {
                   11034:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11035:                     if ($outcome eq 'ok') {
1.1227    raeburn  11036:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11037:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11038:                         }
1.1226    raeburn  11039:                         if (ref($results) eq 'HASH') {
                   11040:                             foreach my $uname (keys(%{$results})) {
                   11041:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11042:                             }
                   11043:                         }
                   11044:                     }
                   11045:                 }
1.612     raeburn  11046:             }
1.1226    raeburn  11047:         } elsif (keys(%{$usershash}) == 1) {
                   11048:             my $user = (keys(%{$usershash}))[0];
                   11049:             my ($uname,$udom) = split(/:/,$user);
                   11050:             if (($udom ne '') && ($uname ne '')) {
                   11051:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11052:                     if (ref($checks) eq 'HASH') {
                   11053:                         if (defined($checks->{'username'})) {
                   11054:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11055:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11056:                         } elsif (defined($checks->{'id'})) {
                   11057:                             if ($usershash->{$user}->{'id'} ne '') {
                   11058:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11059:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11060:                                                                   $usershash->{$user}->{'id'});
                   11061:                             } else {
                   11062:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11063:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11064:                             }
1.585     raeburn  11065:                         }
1.1226    raeburn  11066:                     } else {
                   11067:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11068:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11069:                        return;
                   11070:                     }
                   11071:                     if (!$got_rules->{$udom}) {
                   11072:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11073:                                                                  ['usercreation'],$udom);
                   11074:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11075:                             foreach my $item ('username','id') {
                   11076:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11077:                                    $$curr_rules{$udom}{$item} = 
                   11078:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11079:                                 }
                   11080:                             }
                   11081:                         }
                   11082:                         $got_rules->{$udom} = 1;
1.585     raeburn  11083:                     }
                   11084:                 }
1.1226    raeburn  11085:             } else {
                   11086:                 return;
                   11087:             }
                   11088:         } else {
                   11089:             return;
                   11090:         }
                   11091:         foreach my $user (keys(%{$usershash})) {
                   11092:             my ($uname,$udom) = split(/:/,$user);
                   11093:             next if (($udom eq '') || ($uname eq ''));
                   11094:             my $id;
1.1227    raeburn  11095:             if (ref($inst_results) eq 'HASH') {
                   11096:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11097:                     $id = $inst_results->{$user}->{'id'};
                   11098:                 }
                   11099:             }
                   11100:             if ($id eq '') { 
                   11101:                 if (ref($usershash->{$user})) {
                   11102:                     $id = $usershash->{$user}->{'id'};
                   11103:                 }
1.585     raeburn  11104:             }
1.612     raeburn  11105:             foreach my $item (keys(%{$checks})) {
                   11106:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11107:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11108:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11109:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11110:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11111:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11112:                                 if ($rule_check{$rule}) {
                   11113:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11114:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11115:                                         if (ref($inst_results) eq 'HASH') {
                   11116:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11117:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11118:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11119:                                                 } elsif ($item eq 'id') {
                   11120:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11121:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11122:                                                     }
1.615     raeburn  11123:                                                 }
1.612     raeburn  11124:                                             }
                   11125:                                         }
1.615     raeburn  11126:                                     }
                   11127:                                     last;
1.585     raeburn  11128:                                 }
                   11129:                             }
                   11130:                         }
                   11131:                     }
                   11132:                 }
                   11133:             }
                   11134:         }
                   11135:     }
1.612     raeburn  11136:     return;
                   11137: }
                   11138: 
                   11139: sub user_rule_formats {
                   11140:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11141:     my %text = ( 
                   11142:                  'username' => 'Usernames',
                   11143:                  'id'       => 'IDs',
                   11144:                );
                   11145:     my $output;
                   11146:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11147:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11148:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11149:             $output = '<br />'.
                   11150:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11151:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11152:                       ' <ul>';
1.612     raeburn  11153:             foreach my $rule (@{$ruleorder}) {
                   11154:                 if (ref($curr_rules) eq 'ARRAY') {
                   11155:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11156:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11157:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11158:                                         $rules->{$rule}{'desc'}.'</li>';
                   11159:                         }
                   11160:                     }
                   11161:                 }
                   11162:             }
                   11163:             $output .= '</ul>';
                   11164:         }
                   11165:     }
                   11166:     return $output;
                   11167: }
                   11168: 
                   11169: sub instrule_disallow_msg {
1.615     raeburn  11170:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11171:     my $response;
                   11172:     my %text = (
                   11173:                   item   => 'username',
                   11174:                   items  => 'usernames',
                   11175:                   match  => 'matches',
                   11176:                   do     => 'does',
                   11177:                   action => 'a username',
                   11178:                   one    => 'one',
                   11179:                );
                   11180:     if ($count > 1) {
                   11181:         $text{'item'} = 'usernames';
                   11182:         $text{'match'} ='match';
                   11183:         $text{'do'} = 'do';
                   11184:         $text{'action'} = 'usernames',
                   11185:         $text{'one'} = 'ones';
                   11186:     }
                   11187:     if ($checkitem eq 'id') {
                   11188:         $text{'items'} = 'IDs';
                   11189:         $text{'item'} = 'ID';
                   11190:         $text{'action'} = 'an ID';
1.615     raeburn  11191:         if ($count > 1) {
                   11192:             $text{'item'} = 'IDs';
                   11193:             $text{'action'} = 'IDs';
                   11194:         }
1.612     raeburn  11195:     }
1.674     bisitz   11196:     $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  11197:     if ($mode eq 'upload') {
                   11198:         if ($checkitem eq 'username') {
                   11199:             $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'}.");
                   11200:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11201:             $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  11202:         }
1.669     raeburn  11203:     } elsif ($mode eq 'selfcreate') {
                   11204:         if ($checkitem eq 'id') {
                   11205:             $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.");
                   11206:         }
1.615     raeburn  11207:     } else {
                   11208:         if ($checkitem eq 'username') {
                   11209:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11210:         } elsif ($checkitem eq 'id') {
                   11211:             $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.");
                   11212:         }
1.612     raeburn  11213:     }
                   11214:     return $response;
1.585     raeburn  11215: }
                   11216: 
1.624     raeburn  11217: sub personal_data_fieldtitles {
                   11218:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11219:                         id => 'Student/Employee ID',
                   11220:                         permanentemail => 'E-mail address',
                   11221:                         lastname => 'Last Name',
                   11222:                         firstname => 'First Name',
                   11223:                         middlename => 'Middle Name',
                   11224:                         generation => 'Generation',
                   11225:                         gen => 'Generation',
1.765     raeburn  11226:                         inststatus => 'Affiliation',
1.624     raeburn  11227:                    );
                   11228:     return %fieldtitles;
                   11229: }
                   11230: 
1.642     raeburn  11231: sub sorted_inst_types {
                   11232:     my ($dom) = @_;
1.1185    raeburn  11233:     my ($usertypes,$order);
                   11234:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11235:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11236:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11237:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11238:     } else {
                   11239:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11240:     }
1.642     raeburn  11241:     my $othertitle = &mt('All users');
                   11242:     if ($env{'request.course.id'}) {
1.668     raeburn  11243:         $othertitle  = &mt('Any users');
1.642     raeburn  11244:     }
                   11245:     my @types;
                   11246:     if (ref($order) eq 'ARRAY') {
                   11247:         @types = @{$order};
                   11248:     }
                   11249:     if (@types == 0) {
                   11250:         if (ref($usertypes) eq 'HASH') {
                   11251:             @types = sort(keys(%{$usertypes}));
                   11252:         }
                   11253:     }
                   11254:     if (keys(%{$usertypes}) > 0) {
                   11255:         $othertitle = &mt('Other users');
                   11256:     }
                   11257:     return ($othertitle,$usertypes,\@types);
                   11258: }
                   11259: 
1.645     raeburn  11260: sub get_institutional_codes {
1.1361    raeburn  11261:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11262: # Get complete list of course sections to update
                   11263:     my @currsections = ();
                   11264:     my @currxlists = ();
1.1361    raeburn  11265:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11266:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11267:     my $crskey = $crs.':'.$coursecode;
                   11268:     @{$unclutteredsec{$crskey}} = ();
                   11269:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11270: 
                   11271:     if ($$settings{'internal.sectionnums'} ne '') {
                   11272:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11273:     }
                   11274: 
                   11275:     if ($$settings{'internal.crosslistings'} ne '') {
                   11276:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11277:     }
                   11278: 
                   11279:     if (@currxlists > 0) {
1.1361    raeburn  11280:         foreach my $xl (@currxlists) {
                   11281:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11282:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11283:                     push(@{$allcourses},$1);
1.645     raeburn  11284:                     $$LC_code{$1} = $2;
                   11285:                 }
                   11286:             }
                   11287:         }
                   11288:     }
1.1361    raeburn  11289: 
1.645     raeburn  11290:     if (@currsections > 0) {
1.1361    raeburn  11291:         foreach my $sec (@currsections) {
                   11292:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11293:                 my $instsec = $1;
1.645     raeburn  11294:                 my $lc_sec = $2;
1.1361    raeburn  11295:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11296:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11297:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11298:                 }
                   11299:             }
                   11300:         }
                   11301:     }
                   11302: 
                   11303:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11304:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11305:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11306:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11307:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11308:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11309:                     push(@{$allcourses},$sec);
1.1361    raeburn  11310:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11311:                 }
                   11312:             }
                   11313:         }
                   11314:     }
                   11315:     return;
                   11316: }
                   11317: 
1.971     raeburn  11318: sub get_standard_codeitems {
                   11319:     return ('Year','Semester','Department','Number','Section');
                   11320: }
                   11321: 
1.112     bowersj2 11322: =pod
                   11323: 
1.780     raeburn  11324: =head1 Slot Helpers
                   11325: 
                   11326: =over 4
                   11327: 
                   11328: =item * sorted_slots()
                   11329: 
1.1040    raeburn  11330: Sorts an array of slot names in order of an optional sort key,
                   11331: default sort is by slot start time (earliest first). 
1.780     raeburn  11332: 
                   11333: Inputs:
                   11334: 
                   11335: =over 4
                   11336: 
                   11337: slotsarr  - Reference to array of unsorted slot names.
                   11338: 
                   11339: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11340: 
1.1040    raeburn  11341: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11342: 
1.549     albertel 11343: =back
                   11344: 
1.780     raeburn  11345: Returns:
                   11346: 
                   11347: =over 4
                   11348: 
1.1040    raeburn  11349: sorted   - An array of slot names sorted by a specified sort key 
                   11350:            (default sort key is start time of the slot).
1.780     raeburn  11351: 
                   11352: =back
                   11353: 
                   11354: =cut
                   11355: 
                   11356: 
                   11357: sub sorted_slots {
1.1040    raeburn  11358:     my ($slotsarr,$slots,$sortkey) = @_;
                   11359:     if ($sortkey eq '') {
                   11360:         $sortkey = 'starttime';
                   11361:     }
1.780     raeburn  11362:     my @sorted;
                   11363:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11364:         @sorted =
                   11365:             sort {
                   11366:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11367:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11368:                      }
                   11369:                      if (ref($slots->{$a})) { return -1;}
                   11370:                      if (ref($slots->{$b})) { return 1;}
                   11371:                      return 0;
                   11372:                  } @{$slotsarr};
                   11373:     }
                   11374:     return @sorted;
                   11375: }
                   11376: 
1.1040    raeburn  11377: =pod
                   11378: 
                   11379: =item * get_future_slots()
                   11380: 
                   11381: Inputs:
                   11382: 
                   11383: =over 4
                   11384: 
                   11385: cnum - course number
                   11386: 
                   11387: cdom - course domain
                   11388: 
                   11389: now - current UNIX time
                   11390: 
                   11391: symb - optional symb
                   11392: 
                   11393: =back
                   11394: 
                   11395: Returns:
                   11396: 
                   11397: =over 4
                   11398: 
                   11399: sorted_reservable - ref to array of student_schedulable slots currently 
                   11400:                     reservable, ordered by end date of reservation period.
                   11401: 
                   11402: reservable_now - ref to hash of student_schedulable slots currently
                   11403:                  reservable.
                   11404: 
                   11405:     Keys in inner hash are:
                   11406:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11407:     (b) endreserve: end date of reservation period.
                   11408:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11409:         selected.
1.1040    raeburn  11410: 
                   11411: sorted_future - ref to array of student_schedulable slots reservable in
                   11412:                 the future, ordered by start date of reservation period.
                   11413: 
                   11414: future_reservable - ref to hash of student_schedulable slots reservable
                   11415:                     in the future.
                   11416: 
                   11417:     Keys in inner hash are:
                   11418:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11419:     (b) startreserve: start date of reservation period.
                   11420:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11421:         selected.
1.1040    raeburn  11422: 
                   11423: =back
                   11424: 
                   11425: =cut
                   11426: 
                   11427: sub get_future_slots {
                   11428:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11429:     my $map;
                   11430:     if ($symb) {
                   11431:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11432:     }
1.1040    raeburn  11433:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11434:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11435:     foreach my $slot (keys(%slots)) {
                   11436:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11437:         if ($symb) {
1.1229    raeburn  11438:             if ($slots{$slot}->{'symb'} ne '') {
                   11439:                 my $canuse;
                   11440:                 my %oksymbs;
                   11441:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11442:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11443:                 if ($oksymbs{$symb}) {
                   11444:                     $canuse = 1;
                   11445:                 } else {
                   11446:                     foreach my $item (@slotsymbs) {
                   11447:                         if ($item =~ /\.(page|sequence)$/) {
                   11448:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11449:                             if (($map ne '') && ($map eq $sloturl)) {
                   11450:                                 $canuse = 1;
                   11451:                                 last;
                   11452:                             }
                   11453:                         }
                   11454:                     }
                   11455:                 }
                   11456:                 next unless ($canuse);
                   11457:             }
1.1040    raeburn  11458:         }
                   11459:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11460:             ($slots{$slot}->{'endtime'} > $now)) {
                   11461:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11462:                 my $userallowed = 0;
                   11463:                 if ($slots{$slot}->{'allowedsections'}) {
                   11464:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11465:                     if (!defined($env{'request.role.sec'})
                   11466:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11467:                         $userallowed=1;
                   11468:                     } else {
                   11469:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11470:                             $userallowed=1;
                   11471:                         }
                   11472:                     }
                   11473:                     unless ($userallowed) {
                   11474:                         if (defined($env{'request.course.groups'})) {
                   11475:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11476:                             foreach my $group (@groups) {
                   11477:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11478:                                     $userallowed=1;
                   11479:                                     last;
                   11480:                                 }
                   11481:                             }
                   11482:                         }
                   11483:                     }
                   11484:                 }
                   11485:                 if ($slots{$slot}->{'allowedusers'}) {
                   11486:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11487:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11488:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11489:                         $userallowed = 1;
                   11490:                     }
                   11491:                 }
                   11492:                 next unless($userallowed);
                   11493:             }
                   11494:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11495:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11496:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11497:             my $uniqueperiod;
                   11498:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11499:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11500:             }
1.1040    raeburn  11501:             if (($startreserve < $now) &&
                   11502:                 (!$endreserve || $endreserve > $now)) {
                   11503:                 my $lastres = $endreserve;
                   11504:                 if (!$lastres) {
                   11505:                     $lastres = $slots{$slot}->{'starttime'};
                   11506:                 }
                   11507:                 $reservable_now{$slot} = {
                   11508:                                            symb       => $symb,
1.1250    raeburn  11509:                                            endreserve => $lastres,
                   11510:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11511:                                          };
                   11512:             } elsif (($startreserve > $now) &&
                   11513:                      (!$endreserve || $endreserve > $startreserve)) {
                   11514:                 $future_reservable{$slot} = {
                   11515:                                               symb         => $symb,
1.1250    raeburn  11516:                                               startreserve => $startreserve,
                   11517:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11518:                                             };
                   11519:             }
                   11520:         }
                   11521:     }
                   11522:     my @unsorted_reservable = keys(%reservable_now);
                   11523:     if (@unsorted_reservable > 0) {
                   11524:         @sorted_reservable = 
                   11525:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11526:     }
                   11527:     my @unsorted_future = keys(%future_reservable);
                   11528:     if (@unsorted_future > 0) {
                   11529:         @sorted_future =
                   11530:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11531:     }
                   11532:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11533: }
1.780     raeburn  11534: 
                   11535: =pod
                   11536: 
1.1057    foxr     11537: =back
                   11538: 
1.549     albertel 11539: =head1 HTTP Helpers
                   11540: 
                   11541: =over 4
                   11542: 
1.648     raeburn  11543: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11544: 
1.258     albertel 11545: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11546: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11547: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11548: 
                   11549: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11550: $possible_names is an ref to an array of form element names.  As an example:
                   11551: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11552: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11553: 
                   11554: =cut
1.1       albertel 11555: 
1.6       albertel 11556: sub get_unprocessed_cgi {
1.25      albertel 11557:   my ($query,$possible_names)= @_;
1.26      matthew  11558:   # $Apache::lonxml::debug=1;
1.356     albertel 11559:   foreach my $pair (split(/&/,$query)) {
                   11560:     my ($name, $value) = split(/=/,$pair);
1.369     www      11561:     $name = &unescape($name);
1.25      albertel 11562:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11563:       $value =~ tr/+/ /;
                   11564:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11565:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11566:     }
1.16      harris41 11567:   }
1.6       albertel 11568: }
                   11569: 
1.112     bowersj2 11570: =pod
                   11571: 
1.648     raeburn  11572: =item * &cacheheader() 
1.112     bowersj2 11573: 
                   11574: returns cache-controlling header code
                   11575: 
                   11576: =cut
                   11577: 
1.7       albertel 11578: sub cacheheader {
1.258     albertel 11579:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11580:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11581:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11582:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11583:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11584:     return $output;
1.7       albertel 11585: }
                   11586: 
1.112     bowersj2 11587: =pod
                   11588: 
1.648     raeburn  11589: =item * &no_cache($r) 
1.112     bowersj2 11590: 
                   11591: specifies header code to not have cache
                   11592: 
                   11593: =cut
                   11594: 
1.9       albertel 11595: sub no_cache {
1.216     albertel 11596:     my ($r) = @_;
                   11597:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11598: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11599:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11600:     $r->no_cache(1);
                   11601:     $r->header_out("Expires" => $date);
                   11602:     $r->header_out("Pragma" => "no-cache");
1.123     www      11603: }
                   11604: 
                   11605: sub content_type {
1.181     albertel 11606:     my ($r,$type,$charset) = @_;
1.299     foxr     11607:     if ($r) {
                   11608: 	#  Note that printout.pl calls this with undef for $r.
                   11609: 	&no_cache($r);
                   11610:     }
1.258     albertel 11611:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11612:     unless ($charset) {
                   11613: 	$charset=&Apache::lonlocal::current_encoding;
                   11614:     }
                   11615:     if ($charset) { $type.='; charset='.$charset; }
                   11616:     if ($r) {
                   11617: 	$r->content_type($type);
                   11618:     } else {
                   11619: 	print("Content-type: $type\n\n");
                   11620:     }
1.9       albertel 11621: }
1.25      albertel 11622: 
1.112     bowersj2 11623: =pod
                   11624: 
1.648     raeburn  11625: =item * &add_to_env($name,$value) 
1.112     bowersj2 11626: 
1.258     albertel 11627: adds $name to the %env hash with value
1.112     bowersj2 11628: $value, if $name already exists, the entry is converted to an array
                   11629: reference and $value is added to the array.
                   11630: 
                   11631: =cut
                   11632: 
1.25      albertel 11633: sub add_to_env {
                   11634:   my ($name,$value)=@_;
1.258     albertel 11635:   if (defined($env{$name})) {
                   11636:     if (ref($env{$name})) {
1.25      albertel 11637:       #already have multiple values
1.258     albertel 11638:       push(@{ $env{$name} },$value);
1.25      albertel 11639:     } else {
                   11640:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11641:       my $first=$env{$name};
                   11642:       undef($env{$name});
                   11643:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11644:     }
                   11645:   } else {
1.258     albertel 11646:     $env{$name}=$value;
1.25      albertel 11647:   }
1.31      albertel 11648: }
1.149     albertel 11649: 
                   11650: =pod
                   11651: 
1.648     raeburn  11652: =item * &get_env_multiple($name) 
1.149     albertel 11653: 
1.258     albertel 11654: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11655: values may be defined and end up as an array ref.
                   11656: 
                   11657: returns an array of values
                   11658: 
                   11659: =cut
                   11660: 
                   11661: sub get_env_multiple {
                   11662:     my ($name) = @_;
                   11663:     my @values;
1.258     albertel 11664:     if (defined($env{$name})) {
1.149     albertel 11665:         # exists is it an array
1.258     albertel 11666:         if (ref($env{$name})) {
                   11667:             @values=@{ $env{$name} };
1.149     albertel 11668:         } else {
1.258     albertel 11669:             $values[0]=$env{$name};
1.149     albertel 11670:         }
                   11671:     }
                   11672:     return(@values);
                   11673: }
                   11674: 
1.1249    damieng  11675: # Looks at given dependencies, and returns something depending on the context.
                   11676: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11677: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11678: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11679: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11680: # $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.
                   11681: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11682: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11683: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11684: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11685: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11686: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11687: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11688: # @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)
                   11689: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11690: sub ask_for_embedded_content {
1.1249    damieng  11691:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11692:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11693:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11694:         %currsubfile,%unused,$rem);
1.1071    raeburn  11695:     my $counter = 0;
                   11696:     my $numnew = 0;
1.987     raeburn  11697:     my $numremref = 0;
                   11698:     my $numinvalid = 0;
                   11699:     my $numpathchg = 0;
                   11700:     my $numexisting = 0;
1.1071    raeburn  11701:     my $numunused = 0;
                   11702:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11703:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11704:     my $heading = &mt('Upload embedded files');
                   11705:     my $buttontext = &mt('Upload');
                   11706: 
1.1249    damieng  11707:     # fills these variables based on the context:
                   11708:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11709:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11710:     if ($env{'request.course.id'}) {
1.1123    raeburn  11711:         if ($actionurl eq '/adm/dependencies') {
                   11712:             $navmap = Apache::lonnavmaps::navmap->new();
                   11713:         }
                   11714:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11715:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11716:     }
1.1123    raeburn  11717:     if (($actionurl eq '/adm/portfolio') || 
                   11718:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11719:         my $current_path='/';
                   11720:         if ($env{'form.currentpath'}) {
                   11721:             $current_path = $env{'form.currentpath'};
                   11722:         }
                   11723:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11724:             $udom = $cdom;
                   11725:             $uname = $cnum;
1.984     raeburn  11726:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11727:         } else {
                   11728:             $udom = $env{'user.domain'};
                   11729:             $uname = $env{'user.name'};
                   11730:             $url = '/userfiles/portfolio';
                   11731:         }
1.987     raeburn  11732:         $toplevel = $url.'/';
1.984     raeburn  11733:         $url .= $current_path;
                   11734:         $getpropath = 1;
1.987     raeburn  11735:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11736:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11737:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11738:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11739:         $toplevel = $url;
1.984     raeburn  11740:         if ($rest ne '') {
1.987     raeburn  11741:             $url .= $rest;
                   11742:         }
                   11743:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11744:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11745:             $url = $args->{'docs_url'};
                   11746:             $toplevel = $url;
1.1084    raeburn  11747:             if ($args->{'context'} eq 'paste') {
                   11748:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11749:                 ($path) = 
                   11750:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11751:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11752:                 $fileloc =~ s{^/}{};
                   11753:             }
1.1071    raeburn  11754:         }
1.1084    raeburn  11755:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11756:         if ($env{'request.course.id'} ne '') {
                   11757:             if (ref($args) eq 'HASH') {
                   11758:                 $url = $args->{'docs_url'};
                   11759:                 $title = $args->{'docs_title'};
1.1126    raeburn  11760:                 $toplevel = $url; 
                   11761:                 unless ($toplevel =~ m{^/}) {
                   11762:                     $toplevel = "/$url";
                   11763:                 }
1.1085    raeburn  11764:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11765:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11766:                     $path = $1;
                   11767:                 } else {
                   11768:                     ($path) =
                   11769:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11770:                 }
1.1195    raeburn  11771:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11772:                     $fileloc = $toplevel;
                   11773:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11774:                     my ($udom,$uname,$fname) =
                   11775:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11776:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11777:                 } else {
                   11778:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11779:                 }
1.1071    raeburn  11780:                 $fileloc =~ s{^/}{};
                   11781:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11782:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11783:             }
1.987     raeburn  11784:         }
1.1123    raeburn  11785:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11786:         $udom = $cdom;
                   11787:         $uname = $cnum;
                   11788:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11789:         $toplevel = $url;
                   11790:         $path = $url;
                   11791:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11792:         $fileloc =~ s{^/}{};
1.987     raeburn  11793:     }
1.1249    damieng  11794:     
                   11795:     # parses the dependency paths to get some info
                   11796:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11797:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11798:     # (will be completed later)
                   11799:     # $mapping:
                   11800:     #   for external URLs: external URL -> external URL
                   11801:     #   for relative paths: clean path -> original path
                   11802:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11803:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11804:     foreach my $file (keys(%{$allfiles})) {
                   11805:         my $embed_file;
                   11806:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11807:             $embed_file = $1;
                   11808:         } else {
                   11809:             $embed_file = $file;
                   11810:         }
1.1158    raeburn  11811:         my ($absolutepath,$cleaned_file);
                   11812:         if ($embed_file =~ m{^\w+://}) {
                   11813:             $cleaned_file = $embed_file;
1.1147    raeburn  11814:             $newfiles{$cleaned_file} = 1;
                   11815:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11816:         } else {
1.1158    raeburn  11817:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11818:             if ($embed_file =~ m{^/}) {
                   11819:                 $absolutepath = $embed_file;
                   11820:             }
1.1147    raeburn  11821:             if ($cleaned_file =~ m{/}) {
                   11822:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11823:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11824:                 my $item = $fname;
                   11825:                 if ($path ne '') {
                   11826:                     $item = $path.'/'.$fname;
                   11827:                     $subdependencies{$path}{$fname} = 1;
                   11828:                 } else {
                   11829:                     $dependencies{$item} = 1;
                   11830:                 }
                   11831:                 if ($absolutepath) {
                   11832:                     $mapping{$item} = $absolutepath;
                   11833:                 } else {
                   11834:                     $mapping{$item} = $embed_file;
                   11835:                 }
                   11836:             } else {
                   11837:                 $dependencies{$embed_file} = 1;
                   11838:                 if ($absolutepath) {
1.1147    raeburn  11839:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11840:                 } else {
1.1147    raeburn  11841:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11842:                 }
                   11843:             }
1.984     raeburn  11844:         }
                   11845:     }
1.1249    damieng  11846:     
                   11847:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11848:     # and lists
                   11849:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11850:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11851:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11852:     #                                    the path had to be cleaned up
                   11853:     # $existing: hash clean path -> 1 if the file exists
                   11854:     # $numexisting: number of keys in $existing
                   11855:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11856:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11857:     #                                      dependency subdirectories that are
                   11858:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11859:     my $dirptr = 16384;
1.984     raeburn  11860:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11861:         $currsubfile{$path} = {};
1.1123    raeburn  11862:         if (($actionurl eq '/adm/portfolio') || 
                   11863:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11864:             my ($sublistref,$listerror) =
                   11865:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11866:             if (ref($sublistref) eq 'ARRAY') {
                   11867:                 foreach my $line (@{$sublistref}) {
                   11868:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11869:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11870:                 }
1.984     raeburn  11871:             }
1.987     raeburn  11872:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11873:             if (opendir(my $dir,$url.'/'.$path)) {
                   11874:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11875:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11876:             }
1.1084    raeburn  11877:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11878:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11879:                   ($args->{'context'} eq 'paste')) ||
                   11880:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11881:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11882:                 my $dir;
                   11883:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11884:                     $dir = $fileloc;
                   11885:                 } else {
                   11886:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11887:                 }
1.1071    raeburn  11888:                 if ($dir ne '') {
                   11889:                     my ($sublistref,$listerror) =
                   11890:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11891:                     if (ref($sublistref) eq 'ARRAY') {
                   11892:                         foreach my $line (@{$sublistref}) {
                   11893:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11894:                                 undef,$mtime)=split(/\&/,$line,12);
                   11895:                             unless (($testdir&$dirptr) ||
                   11896:                                     ($file_name =~ /^\.\.?$/)) {
                   11897:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11898:                             }
                   11899:                         }
                   11900:                     }
                   11901:                 }
1.984     raeburn  11902:             }
                   11903:         }
                   11904:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11905:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11906:                 my $item = $path.'/'.$file;
                   11907:                 unless ($mapping{$item} eq $item) {
                   11908:                     $pathchanges{$item} = 1;
                   11909:                 }
                   11910:                 $existing{$item} = 1;
                   11911:                 $numexisting ++;
                   11912:             } else {
                   11913:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11914:             }
                   11915:         }
1.1071    raeburn  11916:         if ($actionurl eq '/adm/dependencies') {
                   11917:             foreach my $path (keys(%currsubfile)) {
                   11918:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11919:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11920:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11921:                              next if (($rem ne '') &&
                   11922:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11923:                                        (ref($navmap) &&
                   11924:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11925:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11926:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11927:                              $unused{$path.'/'.$file} = 1; 
                   11928:                          }
                   11929:                     }
                   11930:                 }
                   11931:             }
                   11932:         }
1.984     raeburn  11933:     }
1.1249    damieng  11934:     
                   11935:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11936:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11937:     my %currfile;
1.1123    raeburn  11938:     if (($actionurl eq '/adm/portfolio') ||
                   11939:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11940:         my ($dirlistref,$listerror) =
                   11941:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11942:         if (ref($dirlistref) eq 'ARRAY') {
                   11943:             foreach my $line (@{$dirlistref}) {
                   11944:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11945:                 $currfile{$file_name} = 1;
                   11946:             }
1.984     raeburn  11947:         }
1.987     raeburn  11948:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11949:         if (opendir(my $dir,$url)) {
1.987     raeburn  11950:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11951:             map {$currfile{$_} = 1;} @dir_list;
                   11952:         }
1.1084    raeburn  11953:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11954:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11955:               ($args->{'context'} eq 'paste')) ||
                   11956:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11957:         if ($env{'request.course.id'} ne '') {
                   11958:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11959:             if ($dir ne '') {
                   11960:                 my ($dirlistref,$listerror) =
                   11961:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11962:                 if (ref($dirlistref) eq 'ARRAY') {
                   11963:                     foreach my $line (@{$dirlistref}) {
                   11964:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11965:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11966:                         unless (($testdir&$dirptr) ||
                   11967:                                 ($file_name =~ /^\.\.?$/)) {
                   11968:                             $currfile{$file_name} = [$size,$mtime];
                   11969:                         }
                   11970:                     }
                   11971:                 }
                   11972:             }
                   11973:         }
1.984     raeburn  11974:     }
1.1249    damieng  11975:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11976:     # are not in subdirectories, using $currfile
1.984     raeburn  11977:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11978:         if (exists($currfile{$file})) {
1.987     raeburn  11979:             unless ($mapping{$file} eq $file) {
                   11980:                 $pathchanges{$file} = 1;
                   11981:             }
                   11982:             $existing{$file} = 1;
                   11983:             $numexisting ++;
                   11984:         } else {
1.984     raeburn  11985:             $newfiles{$file} = 1;
                   11986:         }
                   11987:     }
1.1071    raeburn  11988:     foreach my $file (keys(%currfile)) {
                   11989:         unless (($file eq $filename) ||
                   11990:                 ($file eq $filename.'.bak') ||
                   11991:                 ($dependencies{$file})) {
1.1085    raeburn  11992:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11993:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11994:                     next if (($rem ne '') &&
                   11995:                              (($env{"httpref.$rem".$file} ne '') ||
                   11996:                               (ref($navmap) &&
                   11997:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11998:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11999:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12000:                 }
1.1085    raeburn  12001:             }
1.1071    raeburn  12002:             $unused{$file} = 1;
                   12003:         }
                   12004:     }
1.1249    damieng  12005:     
                   12006:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12007:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12008:         ($args->{'context'} eq 'paste')) {
                   12009:         $counter = scalar(keys(%existing));
                   12010:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12011:         return ($output,$counter,$numpathchg,\%existing);
                   12012:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12013:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12014:         $counter = scalar(keys(%existing));
                   12015:         $numpathchg = scalar(keys(%pathchanges));
                   12016:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12017:     }
1.1249    damieng  12018:     
                   12019:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12020:     
                   12021:     # $upload_output: missing dependencies (with upload form)
                   12022:     # $modify_output: uploaded dependencies (in use)
                   12023:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12024:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12025:         if ($actionurl eq '/adm/dependencies') {
                   12026:             next if ($embed_file =~ m{^\w+://});
                   12027:         }
1.660     raeburn  12028:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12029:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12030:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12031:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12032:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12033:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12034:         }
1.1123    raeburn  12035:         $upload_output .= '</td>';
1.1071    raeburn  12036:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12037:             $upload_output.='<td align="right">'.
                   12038:                             '<span class="LC_info LC_fontsize_medium">'.
                   12039:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12040:             $numremref++;
1.660     raeburn  12041:         } elsif ($args->{'error_on_invalid_names'}
                   12042:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12043:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12044:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12045:             $numinvalid++;
1.660     raeburn  12046:         } else {
1.1123    raeburn  12047:             $upload_output .= '<td>'.
                   12048:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12049:                                                      $embed_file,\%mapping,
1.1071    raeburn  12050:                                                      $allfiles,$codebase,'upload');
                   12051:             $counter ++;
                   12052:             $numnew ++;
1.987     raeburn  12053:         }
                   12054:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12055:     }
                   12056:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12057:         if ($actionurl eq '/adm/dependencies') {
                   12058:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12059:             $modify_output .= &start_data_table_row().
                   12060:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12061:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12062:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12063:                               '<td>'.$size.'</td>'.
                   12064:                               '<td>'.$mtime.'</td>'.
                   12065:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12066:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12067:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12068:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12069:                               &embedded_file_element('upload_embedded',$counter,
                   12070:                                                      $embed_file,\%mapping,
                   12071:                                                      $allfiles,$codebase,'modify').
                   12072:                               '</div></td>'.
                   12073:                               &end_data_table_row()."\n";
                   12074:             $counter ++;
                   12075:         } else {
                   12076:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12077:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12078:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12079:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12080:                               &Apache::loncommon::end_data_table_row()."\n";
                   12081:         }
                   12082:     }
                   12083:     my $delidx = $counter;
                   12084:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12085:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12086:         $delete_output .= &start_data_table_row().
                   12087:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12088:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12089:                           '<td>'.$size.'</td>'.
                   12090:                           '<td>'.$mtime.'</td>'.
                   12091:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12092:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12093:                           &embedded_file_element('upload_embedded',$delidx,
                   12094:                                                  $oldfile,\%mapping,$allfiles,
                   12095:                                                  $codebase,'delete').'</td>'.
                   12096:                           &end_data_table_row()."\n"; 
                   12097:         $numunused ++;
                   12098:         $delidx ++;
1.987     raeburn  12099:     }
                   12100:     if ($upload_output) {
                   12101:         $upload_output = &start_data_table().
                   12102:                          $upload_output.
                   12103:                          &end_data_table()."\n";
                   12104:     }
1.1071    raeburn  12105:     if ($modify_output) {
                   12106:         $modify_output = &start_data_table().
                   12107:                          &start_data_table_header_row().
                   12108:                          '<th>'.&mt('File').'</th>'.
                   12109:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12110:                          '<th>'.&mt('Modified').'</th>'.
                   12111:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12112:                          &end_data_table_header_row().
                   12113:                          $modify_output.
                   12114:                          &end_data_table()."\n";
                   12115:     }
                   12116:     if ($delete_output) {
                   12117:         $delete_output = &start_data_table().
                   12118:                          &start_data_table_header_row().
                   12119:                          '<th>'.&mt('File').'</th>'.
                   12120:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12121:                          '<th>'.&mt('Modified').'</th>'.
                   12122:                          '<th>'.&mt('Delete?').'</th>'.
                   12123:                          &end_data_table_header_row().
                   12124:                          $delete_output.
                   12125:                          &end_data_table()."\n";
                   12126:     }
1.987     raeburn  12127:     my $applies = 0;
                   12128:     if ($numremref) {
                   12129:         $applies ++;
                   12130:     }
                   12131:     if ($numinvalid) {
                   12132:         $applies ++;
                   12133:     }
                   12134:     if ($numexisting) {
                   12135:         $applies ++;
                   12136:     }
1.1071    raeburn  12137:     if ($counter || $numunused) {
1.987     raeburn  12138:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12139:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12140:                   $state.'<h3>'.$heading.'</h3>'; 
                   12141:         if ($actionurl eq '/adm/dependencies') {
                   12142:             if ($numnew) {
                   12143:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12144:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12145:                            $upload_output.'<br />'."\n";
                   12146:             }
                   12147:             if ($numexisting) {
                   12148:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12149:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12150:                            $modify_output.'<br />'."\n";
                   12151:                            $buttontext = &mt('Save changes');
                   12152:             }
                   12153:             if ($numunused) {
                   12154:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12155:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12156:                            $delete_output.'<br />'."\n";
                   12157:                            $buttontext = &mt('Save changes');
                   12158:             }
                   12159:         } else {
                   12160:             $output .= $upload_output.'<br />'."\n";
                   12161:         }
                   12162:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12163:                    $counter.'" />'."\n";
                   12164:         if ($actionurl eq '/adm/dependencies') { 
                   12165:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12166:                        $numnew.'" />'."\n";
                   12167:         } elsif ($actionurl eq '') {
1.987     raeburn  12168:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12169:         }
                   12170:     } elsif ($applies) {
                   12171:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12172:         if ($applies > 1) {
                   12173:             $output .=  
1.1123    raeburn  12174:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12175:             if ($numremref) {
                   12176:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12177:             }
                   12178:             if ($numinvalid) {
                   12179:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12180:             }
                   12181:             if ($numexisting) {
                   12182:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12183:             }
                   12184:             $output .= '</ul><br />';
                   12185:         } elsif ($numremref) {
                   12186:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12187:         } elsif ($numinvalid) {
                   12188:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12189:         } elsif ($numexisting) {
                   12190:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12191:         }
                   12192:         $output .= $upload_output.'<br />';
                   12193:     }
                   12194:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12195:     $chgcount = $counter;
1.987     raeburn  12196:     if (keys(%pathchanges) > 0) {
                   12197:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12198:             if ($counter) {
1.987     raeburn  12199:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12200:                                                   $embed_file,\%mapping,
1.1071    raeburn  12201:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12202:             } else {
                   12203:                 $pathchange_output .= 
                   12204:                     &start_data_table_row().
                   12205:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12206:                     $chgcount.'" checked="checked" /></td>'.
                   12207:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12208:                     '<td>'.$embed_file.
                   12209:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12210:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12211:                     '</td>'.&end_data_table_row();
1.660     raeburn  12212:             }
1.987     raeburn  12213:             $numpathchg ++;
                   12214:             $chgcount ++;
1.660     raeburn  12215:         }
                   12216:     }
1.1127    raeburn  12217:     if (($counter) || ($numunused)) {
1.987     raeburn  12218:         if ($numpathchg) {
                   12219:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12220:                        $numpathchg.'" />'."\n";
                   12221:         }
                   12222:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12223:             ($actionurl eq '/adm/imsimport')) {
                   12224:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12225:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12226:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12227:         } elsif ($actionurl eq '/adm/dependencies') {
                   12228:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12229:         }
1.1123    raeburn  12230:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12231:     } elsif ($numpathchg) {
                   12232:         my %pathchange = ();
                   12233:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12234:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12235:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12236:         }
1.987     raeburn  12237:     }
1.1071    raeburn  12238:     return ($output,$counter,$numpathchg);
1.987     raeburn  12239: }
                   12240: 
1.1147    raeburn  12241: =pod
                   12242: 
                   12243: =item * clean_path($name)
                   12244: 
                   12245: Performs clean-up of directories, subdirectories and filename in an
                   12246: embedded object, referenced in an HTML file which is being uploaded
                   12247: to a course or portfolio, where 
                   12248: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12249: checked.
                   12250: 
                   12251: Clean-up is similar to replacements in lonnet::clean_filename()
                   12252: except each / between sub-directory and next level is preserved.
                   12253: 
                   12254: =cut
                   12255: 
                   12256: sub clean_path {
                   12257:     my ($embed_file) = @_;
                   12258:     $embed_file =~s{^/+}{};
                   12259:     my @contents;
                   12260:     if ($embed_file =~ m{/}) {
                   12261:         @contents = split(/\//,$embed_file);
                   12262:     } else {
                   12263:         @contents = ($embed_file);
                   12264:     }
                   12265:     my $lastidx = scalar(@contents)-1;
                   12266:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12267:         $contents[$i]=~s{\\}{/}g;
                   12268:         $contents[$i]=~s/\s+/\_/g;
                   12269:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12270:         if ($i == $lastidx) {
                   12271:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12272:         }
                   12273:     }
                   12274:     if ($lastidx > 0) {
                   12275:         return join('/',@contents);
                   12276:     } else {
                   12277:         return $contents[0];
                   12278:     }
                   12279: }
                   12280: 
1.987     raeburn  12281: sub embedded_file_element {
1.1071    raeburn  12282:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12283:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12284:                    (ref($codebase) eq 'HASH'));
                   12285:     my $output;
1.1071    raeburn  12286:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12287:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12288:     }
                   12289:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12290:                &escape($embed_file).'" />';
                   12291:     unless (($context eq 'upload_embedded') && 
                   12292:             ($mapping->{$embed_file} eq $embed_file)) {
                   12293:         $output .='
                   12294:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12295:     }
                   12296:     my $attrib;
                   12297:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12298:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12299:     }
                   12300:     $output .=
                   12301:         "\n\t\t".
                   12302:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12303:         $attrib.'" />';
                   12304:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12305:         $output .=
                   12306:             "\n\t\t".
                   12307:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12308:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12309:     }
1.987     raeburn  12310:     return $output;
1.660     raeburn  12311: }
                   12312: 
1.1071    raeburn  12313: sub get_dependency_details {
                   12314:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12315:     my ($size,$mtime,$showsize,$showmtime);
                   12316:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12317:         if ($embed_file =~ m{/}) {
                   12318:             my ($path,$fname) = split(/\//,$embed_file);
                   12319:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12320:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12321:             }
                   12322:         } else {
                   12323:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12324:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12325:             }
                   12326:         }
                   12327:         $showsize = $size/1024.0;
                   12328:         $showsize = sprintf("%.1f",$showsize);
                   12329:         if ($mtime > 0) {
                   12330:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12331:         }
                   12332:     }
                   12333:     return ($showsize,$showmtime);
                   12334: }
                   12335: 
                   12336: sub ask_embedded_js {
                   12337:     return <<"END";
                   12338: <script type="text/javascript"">
                   12339: // <![CDATA[
                   12340: function toggleBrowse(counter) {
                   12341:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12342:     var fileid = document.getElementById('embedded_item_'+counter);
                   12343:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12344:     if (chkboxid.checked == true) {
                   12345:         uploaddivid.style.display='block';
                   12346:     } else {
                   12347:         uploaddivid.style.display='none';
                   12348:         fileid.value = '';
                   12349:     }
                   12350: }
                   12351: // ]]>
                   12352: </script>
                   12353: 
                   12354: END
                   12355: }
                   12356: 
1.661     raeburn  12357: sub upload_embedded {
                   12358:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12359:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12360:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12361:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12362:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12363:         my $orig_uploaded_filename =
                   12364:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12365:         foreach my $type ('orig','ref','attrib','codebase') {
                   12366:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12367:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12368:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12369:             }
                   12370:         }
1.661     raeburn  12371:         my ($path,$fname) =
                   12372:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12373:         # no path, whole string is fname
                   12374:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12375:         $fname = &Apache::lonnet::clean_filename($fname);
                   12376:         # See if there is anything left
                   12377:         next if ($fname eq '');
                   12378: 
                   12379:         # Check if file already exists as a file or directory.
                   12380:         my ($state,$msg);
                   12381:         if ($context eq 'portfolio') {
                   12382:             my $port_path = $dirpath;
                   12383:             if ($group ne '') {
                   12384:                 $port_path = "groups/$group/$port_path";
                   12385:             }
1.987     raeburn  12386:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12387:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12388:                                               $dir_root,$port_path,$disk_quota,
                   12389:                                               $current_disk_usage,$uname,$udom);
                   12390:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12391:                 || $state eq 'file_locked') {
1.661     raeburn  12392:                 $output .= $msg;
                   12393:                 next;
                   12394:             }
                   12395:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12396:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12397:             if ($state eq 'exists') {
                   12398:                 $output .= $msg;
                   12399:                 next;
                   12400:             }
                   12401:         }
                   12402:         # Check if extension is valid
                   12403:         if (($fname =~ /\.(\w+)$/) &&
                   12404:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12405:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12406:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12407:             next;
                   12408:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12409:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12410:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12411:             next;
                   12412:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12413:             $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  12414:             next;
                   12415:         }
                   12416:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12417:         my $subdir = $path;
                   12418:         $subdir =~ s{/+$}{};
1.661     raeburn  12419:         if ($context eq 'portfolio') {
1.984     raeburn  12420:             my $result;
                   12421:             if ($state eq 'existingfile') {
                   12422:                 $result=
                   12423:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12424:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12425:             } else {
1.984     raeburn  12426:                 $result=
                   12427:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12428:                                                     $dirpath.
1.1123    raeburn  12429:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12430:                 if ($result !~ m|^/uploaded/|) {
                   12431:                     $output .= '<span class="LC_error">'
                   12432:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12433:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12434:                                .'</span><br />';
                   12435:                     next;
                   12436:                 } else {
1.987     raeburn  12437:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12438:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12439:                 }
1.661     raeburn  12440:             }
1.1123    raeburn  12441:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12442:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12443:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12444:             my $result =
1.1126    raeburn  12445:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12446:             if ($result !~ m|^/uploaded/|) {
                   12447:                 $output .= '<span class="LC_error">'
                   12448:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12449:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12450:                            .'</span><br />';
                   12451:                     next;
                   12452:             } else {
                   12453:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12454:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12455:                 if ($context eq 'syllabus') {
                   12456:                     &Apache::lonnet::make_public_indefinitely($result);
                   12457:                 }
1.987     raeburn  12458:             }
1.661     raeburn  12459:         } else {
                   12460: # Save the file
                   12461:             my $target = $env{'form.embedded_item_'.$i};
                   12462:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12463:             my $dest = $fullpath.$fname;
                   12464:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12465:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12466:             my $count;
                   12467:             my $filepath = $dir_root;
1.1027    raeburn  12468:             foreach my $subdir (@parts) {
                   12469:                 $filepath .= "/$subdir";
                   12470:                 if (!-e $filepath) {
1.661     raeburn  12471:                     mkdir($filepath,0770);
                   12472:                 }
                   12473:             }
                   12474:             my $fh;
                   12475:             if (!open($fh,'>'.$dest)) {
                   12476:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12477:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12478:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12479:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12480:                            '</span><br />';
                   12481:             } else {
                   12482:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12483:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12484:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12485:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12486:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12487:                               '</span><br />';
                   12488:                 } else {
1.987     raeburn  12489:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12490:                                $url.'</span>').'<br />';
                   12491:                     unless ($context eq 'testbank') {
                   12492:                         $footer .= &mt('View embedded file: [_1]',
                   12493:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12494:                     }
                   12495:                 }
                   12496:                 close($fh);
                   12497:             }
                   12498:         }
                   12499:         if ($env{'form.embedded_ref_'.$i}) {
                   12500:             $pathchange{$i} = 1;
                   12501:         }
                   12502:     }
                   12503:     if ($output) {
                   12504:         $output = '<p>'.$output.'</p>';
                   12505:     }
                   12506:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12507:     $returnflag = 'ok';
1.1071    raeburn  12508:     my $numpathchgs = scalar(keys(%pathchange));
                   12509:     if ($numpathchgs > 0) {
1.987     raeburn  12510:         if ($context eq 'portfolio') {
                   12511:             $output .= '<p>'.&mt('or').'</p>';
                   12512:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12513:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12514:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12515:             $returnflag = 'modify_orightml';
                   12516:         }
                   12517:     }
1.1071    raeburn  12518:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12519: }
                   12520: 
                   12521: sub modify_html_form {
                   12522:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12523:     my $end = 0;
                   12524:     my $modifyform;
                   12525:     if ($context eq 'upload_embedded') {
                   12526:         return unless (ref($pathchange) eq 'HASH');
                   12527:         if ($env{'form.number_embedded_items'}) {
                   12528:             $end += $env{'form.number_embedded_items'};
                   12529:         }
                   12530:         if ($env{'form.number_pathchange_items'}) {
                   12531:             $end += $env{'form.number_pathchange_items'};
                   12532:         }
                   12533:         if ($end) {
                   12534:             for (my $i=0; $i<$end; $i++) {
                   12535:                 if ($i < $env{'form.number_embedded_items'}) {
                   12536:                     next unless($pathchange->{$i});
                   12537:                 }
                   12538:                 $modifyform .=
                   12539:                     &start_data_table_row().
                   12540:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12541:                     'checked="checked" /></td>'.
                   12542:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12543:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12544:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12545:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12546:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12547:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12548:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12549:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12550:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12551:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12552:                     &end_data_table_row();
1.1071    raeburn  12553:             }
1.987     raeburn  12554:         }
                   12555:     } else {
                   12556:         $modifyform = $pathchgtable;
                   12557:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12558:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12559:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12560:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12561:         }
                   12562:     }
                   12563:     if ($modifyform) {
1.1071    raeburn  12564:         if ($actionurl eq '/adm/dependencies') {
                   12565:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12566:         }
1.987     raeburn  12567:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12568:                '<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".
                   12569:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12570:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12571:                '</ol></p>'."\n".'<p>'.
                   12572:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12573:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12574:                &start_data_table()."\n".
                   12575:                &start_data_table_header_row().
                   12576:                '<th>'.&mt('Change?').'</th>'.
                   12577:                '<th>'.&mt('Current reference').'</th>'.
                   12578:                '<th>'.&mt('Required reference').'</th>'.
                   12579:                &end_data_table_header_row()."\n".
                   12580:                $modifyform.
                   12581:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12582:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12583:                '</form>'."\n";
                   12584:     }
                   12585:     return;
                   12586: }
                   12587: 
                   12588: sub modify_html_refs {
1.1123    raeburn  12589:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12590:     my $container;
                   12591:     if ($context eq 'portfolio') {
                   12592:         $container = $env{'form.container'};
                   12593:     } elsif ($context eq 'coursedoc') {
                   12594:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12595:     } elsif ($context eq 'manage_dependencies') {
                   12596:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12597:         $container = "/$container";
1.1123    raeburn  12598:     } elsif ($context eq 'syllabus') {
                   12599:         $container = $url;
1.987     raeburn  12600:     } else {
1.1027    raeburn  12601:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12602:     }
                   12603:     my (%allfiles,%codebase,$output,$content);
                   12604:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12605:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12606:         if (wantarray) {
                   12607:             return ('',0,0); 
                   12608:         } else {
                   12609:             return;
                   12610:         }
                   12611:     }
                   12612:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12613:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12614:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12615:             if (wantarray) {
                   12616:                 return ('',0,0);
                   12617:             } else {
                   12618:                 return;
                   12619:             }
                   12620:         } 
1.987     raeburn  12621:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12622:         if ($content eq '-1') {
                   12623:             if (wantarray) {
                   12624:                 return ('',0,0);
                   12625:             } else {
                   12626:                 return;
                   12627:             }
                   12628:         }
1.987     raeburn  12629:     } else {
1.1071    raeburn  12630:         unless ($container =~ /^\Q$dir_root\E/) {
                   12631:             if (wantarray) {
                   12632:                 return ('',0,0);
                   12633:             } else {
                   12634:                 return;
                   12635:             }
                   12636:         } 
1.1317    raeburn  12637:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12638:             $content = join('', <$fh>);
                   12639:             close($fh);
                   12640:         } else {
1.1071    raeburn  12641:             if (wantarray) {
                   12642:                 return ('',0,0);
                   12643:             } else {
                   12644:                 return;
                   12645:             }
1.987     raeburn  12646:         }
                   12647:     }
                   12648:     my ($count,$codebasecount) = (0,0);
                   12649:     my $mm = new File::MMagic;
                   12650:     my $mime_type = $mm->checktype_contents($content);
                   12651:     if ($mime_type eq 'text/html') {
                   12652:         my $parse_result = 
                   12653:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12654:                                                     \%codebase,\$content);
                   12655:         if ($parse_result eq 'ok') {
                   12656:             foreach my $i (@changes) {
                   12657:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12658:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12659:                 if ($allfiles{$ref}) {
                   12660:                     my $newname =  $orig;
                   12661:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12662:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12663:                     if ($attrib_regexp =~ /:/) {
                   12664:                         $attrib_regexp =~ s/\:/|/g;
                   12665:                     }
                   12666:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12667:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12668:                         $count += $numchg;
1.1123    raeburn  12669:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12670:                         delete($allfiles{$ref});
1.987     raeburn  12671:                     }
                   12672:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12673:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12674:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12675:                         $codebasecount ++;
                   12676:                     }
                   12677:                 }
                   12678:             }
1.1123    raeburn  12679:             my $skiprewrites;
1.987     raeburn  12680:             if ($count || $codebasecount) {
                   12681:                 my $saveresult;
1.1071    raeburn  12682:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12683:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12684:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12685:                     if ($url eq $container) {
                   12686:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12687:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12688:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12689:                                             $fname.'</span>').'</p>';
1.987     raeburn  12690:                     } else {
                   12691:                          $output = '<p class="LC_error">'.
                   12692:                                    &mt('Error: update failed for: [_1].',
                   12693:                                    '<span class="LC_filename">'.
                   12694:                                    $container.'</span>').'</p>';
                   12695:                     }
1.1123    raeburn  12696:                     if ($context eq 'syllabus') {
                   12697:                         unless ($saveresult eq 'ok') {
                   12698:                             $skiprewrites = 1;
                   12699:                         }
                   12700:                     }
1.987     raeburn  12701:                 } else {
1.1317    raeburn  12702:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12703:                         print $fh $content;
                   12704:                         close($fh);
                   12705:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12706:                                   $count,'<span class="LC_filename">'.
                   12707:                                   $container.'</span>').'</p>';
1.661     raeburn  12708:                     } else {
1.987     raeburn  12709:                          $output = '<p class="LC_error">'.
                   12710:                                    &mt('Error: could not update [_1].',
                   12711:                                    '<span class="LC_filename">'.
                   12712:                                    $container.'</span>').'</p>';
1.661     raeburn  12713:                     }
                   12714:                 }
                   12715:             }
1.1123    raeburn  12716:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12717:                 my ($actionurl,$state);
                   12718:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12719:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12720:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12721:                                               \%codebase,
                   12722:                                               {'context' => 'rewrites',
                   12723:                                                'ignore_remote_references' => 1,});
                   12724:                 if (ref($mapping) eq 'HASH') {
                   12725:                     my $rewrites = 0;
                   12726:                     foreach my $key (keys(%{$mapping})) {
                   12727:                         next if ($key =~ m{^https?://});
                   12728:                         my $ref = $mapping->{$key};
                   12729:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12730:                         my $attrib;
                   12731:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12732:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12733:                         }
                   12734:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12735:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12736:                             $rewrites += $numchg;
                   12737:                         }
                   12738:                     }
                   12739:                     if ($rewrites) {
                   12740:                         my $saveresult; 
                   12741:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12742:                         if ($url eq $container) {
                   12743:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12744:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12745:                                             $count,'<span class="LC_filename">'.
                   12746:                                             $fname.'</span>').'</p>';
                   12747:                         } else {
                   12748:                             $output .= '<p class="LC_error">'.
                   12749:                                        &mt('Error: could not update links in [_1].',
                   12750:                                        '<span class="LC_filename">'.
                   12751:                                        $container.'</span>').'</p>';
                   12752: 
                   12753:                         }
                   12754:                     }
                   12755:                 }
                   12756:             }
1.987     raeburn  12757:         } else {
                   12758:             &logthis('Failed to parse '.$container.
                   12759:                      ' to modify references: '.$parse_result);
1.661     raeburn  12760:         }
                   12761:     }
1.1071    raeburn  12762:     if (wantarray) {
                   12763:         return ($output,$count,$codebasecount);
                   12764:     } else {
                   12765:         return $output;
                   12766:     }
1.661     raeburn  12767: }
                   12768: 
                   12769: sub check_for_existing {
                   12770:     my ($path,$fname,$element) = @_;
                   12771:     my ($state,$msg);
                   12772:     if (-d $path.'/'.$fname) {
                   12773:         $state = 'exists';
                   12774:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12775:     } elsif (-e $path.'/'.$fname) {
                   12776:         $state = 'exists';
                   12777:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12778:     }
                   12779:     if ($state eq 'exists') {
                   12780:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12781:     }
                   12782:     return ($state,$msg);
                   12783: }
                   12784: 
                   12785: sub check_for_upload {
                   12786:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12787:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12788:     my $filesize = length($env{'form.'.$element});
                   12789:     if (!$filesize) {
                   12790:         my $msg = '<span class="LC_error">'.
                   12791:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12792:                       '<span class="LC_filename">'.$fname.'</span>',
                   12793:                       $filesize).'<br />'.
1.1007    raeburn  12794:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12795:                   '</span>';
                   12796:         return ('zero_bytes',$msg);
                   12797:     }
                   12798:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12799:     my $getpropath = 1;
1.1021    raeburn  12800:     my ($dirlistref,$listerror) =
                   12801:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12802:     my $found_file = 0;
                   12803:     my $locked_file = 0;
1.991     raeburn  12804:     my @lockers;
                   12805:     my $navmap;
                   12806:     if ($env{'request.course.id'}) {
                   12807:         $navmap = Apache::lonnavmaps::navmap->new();
                   12808:     }
1.1021    raeburn  12809:     if (ref($dirlistref) eq 'ARRAY') {
                   12810:         foreach my $line (@{$dirlistref}) {
                   12811:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12812:             if ($file_name eq $fname){
                   12813:                 $file_name = $path.$file_name;
                   12814:                 if ($group ne '') {
                   12815:                     $file_name = $group.$file_name;
                   12816:                 }
                   12817:                 $found_file = 1;
                   12818:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12819:                     foreach my $lock (@lockers) {
                   12820:                         if (ref($lock) eq 'ARRAY') {
                   12821:                             my ($symb,$crsid) = @{$lock};
                   12822:                             if ($crsid eq $env{'request.course.id'}) {
                   12823:                                 if (ref($navmap)) {
                   12824:                                     my $res = $navmap->getBySymb($symb);
                   12825:                                     foreach my $part (@{$res->parts()}) { 
                   12826:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12827:                                         unless (($slot_status == $res->RESERVED) ||
                   12828:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12829:                                             $locked_file = 1;
                   12830:                                         }
1.991     raeburn  12831:                                     }
1.1021    raeburn  12832:                                 } else {
                   12833:                                     $locked_file = 1;
1.991     raeburn  12834:                                 }
                   12835:                             } else {
                   12836:                                 $locked_file = 1;
                   12837:                             }
                   12838:                         }
1.1021    raeburn  12839:                    }
                   12840:                 } else {
                   12841:                     my @info = split(/\&/,$rest);
                   12842:                     my $currsize = $info[6]/1000;
                   12843:                     if ($currsize < $filesize) {
                   12844:                         my $extra = $filesize - $currsize;
                   12845:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12846:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12847:                                       &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   12848:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12849:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12850:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12851:                             return ('will_exceed_quota',$msg);
                   12852:                         }
1.984     raeburn  12853:                     }
                   12854:                 }
1.661     raeburn  12855:             }
                   12856:         }
                   12857:     }
                   12858:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12859:         my $msg = '<p class="LC_warning">'.
                   12860:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12861:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12862:         return ('will_exceed_quota',$msg);
                   12863:     } elsif ($found_file) {
                   12864:         if ($locked_file) {
1.1179    bisitz   12865:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12866:             $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   12867:             $msg .= '</p>';
1.661     raeburn  12868:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12869:             return ('file_locked',$msg);
                   12870:         } else {
1.1179    bisitz   12871:             my $msg = '<p class="LC_error">';
1.984     raeburn  12872:             $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   12873:             $msg .= '</p>';
1.984     raeburn  12874:             return ('existingfile',$msg);
1.661     raeburn  12875:         }
                   12876:     }
                   12877: }
                   12878: 
1.987     raeburn  12879: sub check_for_traversal {
                   12880:     my ($path,$url,$toplevel) = @_;
                   12881:     my @parts=split(/\//,$path);
                   12882:     my $cleanpath;
                   12883:     my $fullpath = $url;
                   12884:     for (my $i=0;$i<@parts;$i++) {
                   12885:         next if ($parts[$i] eq '.');
                   12886:         if ($parts[$i] eq '..') {
                   12887:             $fullpath =~ s{([^/]+/)$}{};
                   12888:         } else {
                   12889:             $fullpath .= $parts[$i].'/';
                   12890:         }
                   12891:     }
                   12892:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12893:         $cleanpath = $1;
                   12894:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12895:         my $curr_toprel = $1;
                   12896:         my @parts = split(/\//,$curr_toprel);
                   12897:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12898:         my @urlparts = split(/\//,$url_toprel);
                   12899:         my $doubledots;
                   12900:         my $startdiff = -1;
                   12901:         for (my $i=0; $i<@urlparts; $i++) {
                   12902:             if ($startdiff == -1) {
                   12903:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12904:                     $startdiff = $i;
                   12905:                     $doubledots .= '../';
                   12906:                 }
                   12907:             } else {
                   12908:                 $doubledots .= '../';
                   12909:             }
                   12910:         }
                   12911:         if ($startdiff > -1) {
                   12912:             $cleanpath = $doubledots;
                   12913:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12914:                 $cleanpath .= $parts[$i].'/';
                   12915:             }
                   12916:         }
                   12917:     }
                   12918:     $cleanpath =~ s{(/)$}{};
                   12919:     return $cleanpath;
                   12920: }
1.31      albertel 12921: 
1.1053    raeburn  12922: sub is_archive_file {
                   12923:     my ($mimetype) = @_;
                   12924:     if (($mimetype eq 'application/octet-stream') ||
                   12925:         ($mimetype eq 'application/x-stuffit') ||
                   12926:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12927:         return 1;
                   12928:     }
                   12929:     return;
                   12930: }
                   12931: 
                   12932: sub decompress_form {
1.1065    raeburn  12933:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12934:     my %lt = &Apache::lonlocal::texthash (
                   12935:         this => 'This file is an archive file.',
1.1067    raeburn  12936:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12937:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12938:         youm => 'You may wish to extract its contents.',
                   12939:         extr => 'Extract contents',
1.1067    raeburn  12940:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12941:         proa => 'Process automatically?',
1.1053    raeburn  12942:         yes  => 'Yes',
                   12943:         no   => 'No',
1.1067    raeburn  12944:         fold => 'Title for folder containing movie',
                   12945:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12946:     );
1.1065    raeburn  12947:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12948:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12949:     my $info = &list_archive_contents($fileloc,\@paths);
                   12950:     if (@paths) {
                   12951:         foreach my $path (@paths) {
                   12952:             $path =~ s{^/}{};
1.1067    raeburn  12953:             if ($path =~ m{^([^/]+)/$}) {
                   12954:                 $topdir = $1;
                   12955:             }
1.1065    raeburn  12956:             if ($path =~ m{^([^/]+)/}) {
                   12957:                 $toplevel{$1} = $path;
                   12958:             } else {
                   12959:                 $toplevel{$path} = $path;
                   12960:             }
                   12961:         }
                   12962:     }
1.1067    raeburn  12963:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12964:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12965:                         "$topdir/media/",
                   12966:                         "$topdir/media/$topdir.mp4",
                   12967:                         "$topdir/media/FirstFrame.png",
                   12968:                         "$topdir/media/player.swf",
                   12969:                         "$topdir/media/swfobject.js",
                   12970:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12971:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12972:                          "$topdir/$topdir.mp4",
                   12973:                          "$topdir/$topdir\_config.xml",
                   12974:                          "$topdir/$topdir\_controller.swf",
                   12975:                          "$topdir/$topdir\_embed.css",
                   12976:                          "$topdir/$topdir\_First_Frame.png",
                   12977:                          "$topdir/$topdir\_player.html",
                   12978:                          "$topdir/$topdir\_Thumbnails.png",
                   12979:                          "$topdir/playerProductInstall.swf",
                   12980:                          "$topdir/scripts/",
                   12981:                          "$topdir/scripts/config_xml.js",
                   12982:                          "$topdir/scripts/handlebars.js",
                   12983:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12984:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12985:                          "$topdir/scripts/modernizr.js",
                   12986:                          "$topdir/scripts/player-min.js",
                   12987:                          "$topdir/scripts/swfobject.js",
                   12988:                          "$topdir/skins/",
                   12989:                          "$topdir/skins/configuration_express.xml",
                   12990:                          "$topdir/skins/express_show/",
                   12991:                          "$topdir/skins/express_show/player-min.css",
                   12992:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12993:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12994:                          "$topdir/$topdir.mp4",
                   12995:                          "$topdir/$topdir\_config.xml",
                   12996:                          "$topdir/$topdir\_controller.swf",
                   12997:                          "$topdir/$topdir\_embed.css",
                   12998:                          "$topdir/$topdir\_First_Frame.png",
                   12999:                          "$topdir/$topdir\_player.html",
                   13000:                          "$topdir/$topdir\_Thumbnails.png",
                   13001:                          "$topdir/playerProductInstall.swf",
                   13002:                          "$topdir/scripts/",
                   13003:                          "$topdir/scripts/config_xml.js",
                   13004:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13005:                          "$topdir/skins/",
                   13006:                          "$topdir/skins/configuration_express.xml",
                   13007:                          "$topdir/skins/express_show/",
                   13008:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13009:                          "$topdir/skins/express_show/spritesheet.png",
                   13010:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13011:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13012:         if (@diffs == 0) {
1.1164    raeburn  13013:             $is_camtasia = 6;
                   13014:         } else {
1.1197    raeburn  13015:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13016:             if (@diffs == 0) {
                   13017:                 $is_camtasia = 8;
1.1197    raeburn  13018:             } else {
                   13019:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13020:                 if (@diffs == 0) {
                   13021:                     $is_camtasia = 8;
                   13022:                 }
1.1164    raeburn  13023:             }
1.1067    raeburn  13024:         }
                   13025:     }
                   13026:     my $output;
                   13027:     if ($is_camtasia) {
                   13028:         $output = <<"ENDCAM";
                   13029: <script type="text/javascript" language="Javascript">
                   13030: // <![CDATA[
                   13031: 
                   13032: function camtasiaToggle() {
                   13033:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13034:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13035:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13036:                 document.getElementById('camtasia_titles').style.display='block';
                   13037:             } else {
                   13038:                 document.getElementById('camtasia_titles').style.display='none';
                   13039:             }
                   13040:         }
                   13041:     }
                   13042:     return;
                   13043: }
                   13044: 
                   13045: // ]]>
                   13046: </script>
                   13047: <p>$lt{'camt'}</p>
                   13048: ENDCAM
1.1065    raeburn  13049:     } else {
1.1067    raeburn  13050:         $output = '<p>'.$lt{'this'};
                   13051:         if ($info eq '') {
                   13052:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13053:         } else {
                   13054:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13055:                        '<div><pre>'.$info.'</pre></div>';
                   13056:         }
1.1065    raeburn  13057:     }
1.1067    raeburn  13058:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13059:     my $duplicates;
                   13060:     my $num = 0;
                   13061:     if (ref($dirlist) eq 'ARRAY') {
                   13062:         foreach my $item (@{$dirlist}) {
                   13063:             if (ref($item) eq 'ARRAY') {
                   13064:                 if (exists($toplevel{$item->[0]})) {
                   13065:                     $duplicates .= 
                   13066:                         &start_data_table_row().
                   13067:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13068:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13069:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13070:                         'value="1" />'.&mt('Yes').'</label>'.
                   13071:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13072:                         '<td>'.$item->[0].'</td>';
                   13073:                     if ($item->[2]) {
                   13074:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13075:                     } else {
                   13076:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13077:                     }
                   13078:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13079:                                    '<td>'.
                   13080:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13081:                                    '</td>'.
                   13082:                                    &end_data_table_row();
                   13083:                     $num ++;
                   13084:                 }
                   13085:             }
                   13086:         }
                   13087:     }
                   13088:     my $itemcount;
                   13089:     if (@paths > 0) {
                   13090:         $itemcount = scalar(@paths);
                   13091:     } else {
                   13092:         $itemcount = 1;
                   13093:     }
1.1067    raeburn  13094:     if ($is_camtasia) {
                   13095:         $output .= $lt{'auto'}.'<br />'.
                   13096:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13097:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13098:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13099:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13100:                    $lt{'no'}.'</label></span><br />'.
                   13101:                    '<div id="camtasia_titles" style="display:block">'.
                   13102:                    &Apache::lonhtmlcommon::start_pick_box().
                   13103:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13104:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13105:                    &Apache::lonhtmlcommon::row_closure().
                   13106:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13107:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13108:                    &Apache::lonhtmlcommon::row_closure(1).
                   13109:                    &Apache::lonhtmlcommon::end_pick_box().
                   13110:                    '</div>';
                   13111:     }
1.1065    raeburn  13112:     $output .= 
                   13113:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13114:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13115:         "\n";
1.1065    raeburn  13116:     if ($duplicates ne '') {
                   13117:         $output .= '<p><span class="LC_warning">'.
                   13118:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13119:                    &start_data_table().
                   13120:                    &start_data_table_header_row().
                   13121:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13122:                    '<th>'.&mt('Name').'</th>'.
                   13123:                    '<th>'.&mt('Type').'</th>'.
                   13124:                    '<th>'.&mt('Size').'</th>'.
                   13125:                    '<th>'.&mt('Last modified').'</th>'.
                   13126:                    &end_data_table_header_row().
                   13127:                    $duplicates.
                   13128:                    &end_data_table().
                   13129:                    '</p>';
                   13130:     }
1.1067    raeburn  13131:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13132:     if (ref($hiddenelements) eq 'HASH') {
                   13133:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13134:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13135:         }
                   13136:     }
                   13137:     $output .= <<"END";
1.1067    raeburn  13138: <br />
1.1053    raeburn  13139: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13140: </form>
                   13141: $noextract
                   13142: END
                   13143:     return $output;
                   13144: }
                   13145: 
1.1065    raeburn  13146: sub decompression_utility {
                   13147:     my ($program) = @_;
                   13148:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13149:     my $location;
                   13150:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13151:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13152:                          '/usr/sbin/') {
                   13153:             if (-x $dir.$program) {
                   13154:                 $location = $dir.$program;
                   13155:                 last;
                   13156:             }
                   13157:         }
                   13158:     }
                   13159:     return $location;
                   13160: }
                   13161: 
                   13162: sub list_archive_contents {
                   13163:     my ($file,$pathsref) = @_;
                   13164:     my (@cmd,$output);
                   13165:     my $needsregexp;
                   13166:     if ($file =~ /\.zip$/) {
                   13167:         @cmd = (&decompression_utility('unzip'),"-l");
                   13168:         $needsregexp = 1;
                   13169:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13170:              ($file =~ /\.tgz$/)) {
                   13171:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13172:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13173:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13174:     } elsif ($file =~ m|\.tar$|) {
                   13175:         @cmd = (&decompression_utility('tar'),"-tf");
                   13176:     }
                   13177:     if (@cmd) {
                   13178:         undef($!);
                   13179:         undef($@);
                   13180:         if (open(my $fh,"-|", @cmd, $file)) {
                   13181:             while (my $line = <$fh>) {
                   13182:                 $output .= $line;
                   13183:                 chomp($line);
                   13184:                 my $item;
                   13185:                 if ($needsregexp) {
                   13186:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13187:                 } else {
                   13188:                     $item = $line;
                   13189:                 }
                   13190:                 if ($item ne '') {
                   13191:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13192:                         push(@{$pathsref},$item);
                   13193:                     } 
                   13194:                 }
                   13195:             }
                   13196:             close($fh);
                   13197:         }
                   13198:     }
                   13199:     return $output;
                   13200: }
                   13201: 
1.1053    raeburn  13202: sub decompress_uploaded_file {
                   13203:     my ($file,$dir) = @_;
                   13204:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13205:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13206:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13207:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13208:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13209:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13210:     my $decompressed = $env{'cgi.decompressed'};
                   13211:     &Apache::lonnet::delenv('cgi.file');
                   13212:     &Apache::lonnet::delenv('cgi.dir');
                   13213:     &Apache::lonnet::delenv('cgi.decompressed');
                   13214:     return ($decompressed,$result);
                   13215: }
                   13216: 
1.1055    raeburn  13217: sub process_decompression {
                   13218:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13219:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13220:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13221:                &mt('Unexpected file path.').'</p>'."\n";
                   13222:     }
                   13223:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13224:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13225:                &mt('Unexpected course context.').'</p>'."\n";
                   13226:     }
1.1293    raeburn  13227:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13228:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13229:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13230:     }
1.1055    raeburn  13231:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13232:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13233:         $error = &mt('Filename not a supported archive file type.').
                   13234:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13235:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13236:     } else {
                   13237:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13238:         if ($docuhome eq 'no_host') {
                   13239:             $error = &mt('Could not determine home server for course.');
                   13240:         } else {
                   13241:             my @ids=&Apache::lonnet::current_machine_ids();
                   13242:             my $currdir = "$dir_root/$destination";
                   13243:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13244:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13245:                        "$dir_root/$destination";
                   13246:             } else {
                   13247:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13248:                        "$dir_root/$docudom/$docuname/$destination";
                   13249:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13250:                     $error = &mt('Archive file not found.');
                   13251:                 }
                   13252:             }
1.1065    raeburn  13253:             my (@to_overwrite,@to_skip);
                   13254:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13255:                 my $total = $env{'form.archive_overwrite_total'};
                   13256:                 for (my $i=0; $i<$total; $i++) {
                   13257:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13258:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13259:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13260:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13261:                     }
                   13262:                 }
                   13263:             }
                   13264:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13265:             my $numoverwrite = scalar(@to_overwrite);
                   13266:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13267:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13268:             } elsif ($dir eq '') {
1.1055    raeburn  13269:                 $error = &mt('Directory containing archive file unavailable.');
                   13270:             } elsif (!$error) {
1.1065    raeburn  13271:                 my ($decompressed,$display);
1.1292    raeburn  13272:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13273:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13274:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13275:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13276:                         ($decompressed,$display) = 
                   13277:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13278:                         foreach my $item (@to_skip) {
                   13279:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13280:                                 if (-f "$dir/$tempdir/$item") { 
                   13281:                                     unlink("$dir/$tempdir/$item");
                   13282:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13283:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13284:                                 }
                   13285:                             }
                   13286:                         }
                   13287:                         foreach my $item (@to_overwrite) {
                   13288:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13289:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13290:                                     if (-f "$dir/$item") {
                   13291:                                         unlink("$dir/$item");
                   13292:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13293:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13294:                                     }
                   13295:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13296:                                 }
1.1065    raeburn  13297:                             }
                   13298:                         }
1.1292    raeburn  13299:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13300:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13301:                         }
1.1065    raeburn  13302:                     }
                   13303:                 } else {
                   13304:                     ($decompressed,$display) = 
                   13305:                         &decompress_uploaded_file($file,$dir);
                   13306:                 }
1.1055    raeburn  13307:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13308:                     $output = '<p class="LC_info">'.
                   13309:                               &mt('Files extracted successfully from archive.').
                   13310:                               '</p>'."\n";
1.1055    raeburn  13311:                     my ($warning,$result,@contents);
                   13312:                     my ($newdirlistref,$newlisterror) =
                   13313:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13314:                                                  $docuname,1);
                   13315:                     my (%is_dir,%changes,@newitems);
                   13316:                     my $dirptr = 16384;
1.1065    raeburn  13317:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13318:                         foreach my $dir_line (@{$newdirlistref}) {
                   13319:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13320:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13321:                                 push(@newitems,$item);
                   13322:                                 if ($dirptr&$testdir) {
                   13323:                                     $is_dir{$item} = 1;
                   13324:                                 }
                   13325:                                 $changes{$item} = 1;
                   13326:                             }
                   13327:                         }
                   13328:                     }
                   13329:                     if (keys(%changes) > 0) {
                   13330:                         foreach my $item (sort(@newitems)) {
                   13331:                             if ($changes{$item}) {
                   13332:                                 push(@contents,$item);
                   13333:                             }
                   13334:                         }
                   13335:                     }
                   13336:                     if (@contents > 0) {
1.1067    raeburn  13337:                         my $wantform;
                   13338:                         unless ($env{'form.autoextract_camtasia'}) {
                   13339:                             $wantform = 1;
                   13340:                         }
1.1056    raeburn  13341:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13342:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13343:                                                                 $currdir,\%is_dir,
                   13344:                                                                 \%children,\%parent,
1.1056    raeburn  13345:                                                                 \@contents,\%dirorder,
                   13346:                                                                 \%titles,$wantform);
1.1055    raeburn  13347:                         if ($datatable ne '') {
                   13348:                             $output .= &archive_options_form('decompressed',$datatable,
                   13349:                                                              $count,$hiddenelem);
1.1065    raeburn  13350:                             my $startcount = 6;
1.1055    raeburn  13351:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13352:                                                            \%titles,\%children);
1.1055    raeburn  13353:                         }
1.1067    raeburn  13354:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13355:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13356:                             my %displayed;
                   13357:                             my $total = 1;
                   13358:                             $env{'form.archive_directory'} = [];
                   13359:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13360:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13361:                                 $path =~ s{/$}{};
                   13362:                                 my $item;
                   13363:                                 if ($path ne '') {
                   13364:                                     $item = "$path/$titles{$i}";
                   13365:                                 } else {
                   13366:                                     $item = $titles{$i};
                   13367:                                 }
                   13368:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13369:                                 if ($item eq $contents[0]) {
                   13370:                                     push(@{$env{'form.archive_directory'}},$i);
                   13371:                                     $env{'form.archive_'.$i} = 'display';
                   13372:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13373:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13374:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13375:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13376:                                     $env{'form.archive_'.$i} = 'display';
                   13377:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13378:                                     $displayed{'web'} = $i;
                   13379:                                 } else {
1.1164    raeburn  13380:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13381:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13382:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13383:                                         push(@{$env{'form.archive_directory'}},$i);
                   13384:                                     }
                   13385:                                     $env{'form.archive_'.$i} = 'dependency';
                   13386:                                 }
                   13387:                                 $total ++;
                   13388:                             }
                   13389:                             for (my $i=1; $i<$total; $i++) {
                   13390:                                 next if ($i == $displayed{'web'});
                   13391:                                 next if ($i == $displayed{'folder'});
                   13392:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13393:                             }
                   13394:                             $env{'form.phase'} = 'decompress_cleanup';
                   13395:                             $env{'form.archivedelete'} = 1;
                   13396:                             $env{'form.archive_count'} = $total-1;
                   13397:                             $output .=
                   13398:                                 &process_extracted_files('coursedocs',$docudom,
                   13399:                                                          $docuname,$destination,
                   13400:                                                          $dir_root,$hiddenelem);
                   13401:                         }
1.1055    raeburn  13402:                     } else {
                   13403:                         $warning = &mt('No new items extracted from archive file.');
                   13404:                     }
                   13405:                 } else {
                   13406:                     $output = $display;
                   13407:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13408:                 }
                   13409:             }
                   13410:         }
                   13411:     }
                   13412:     if ($error) {
                   13413:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13414:                    $error.'</p>'."\n";
                   13415:     }
                   13416:     if ($warning) {
                   13417:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13418:     }
                   13419:     return $output;
                   13420: }
                   13421: 
                   13422: sub get_extracted {
1.1056    raeburn  13423:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13424:         $titles,$wantform) = @_;
1.1055    raeburn  13425:     my $count = 0;
                   13426:     my $depth = 0;
                   13427:     my $datatable;
1.1056    raeburn  13428:     my @hierarchy;
1.1055    raeburn  13429:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13430:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13431:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13432:     foreach my $item (@{$contents}) {
                   13433:         $count ++;
1.1056    raeburn  13434:         @{$dirorder->{$count}} = @hierarchy;
                   13435:         $titles->{$count} = $item;
1.1055    raeburn  13436:         &archive_hierarchy($depth,$count,$parent,$children);
                   13437:         if ($wantform) {
                   13438:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13439:                                        $currdir,$depth,$count);
                   13440:         }
                   13441:         if ($is_dir->{$item}) {
                   13442:             $depth ++;
1.1056    raeburn  13443:             push(@hierarchy,$count);
                   13444:             $parent->{$depth} = $count;
1.1055    raeburn  13445:             $datatable .=
                   13446:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13447:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13448:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13449:             $depth --;
1.1056    raeburn  13450:             pop(@hierarchy);
1.1055    raeburn  13451:         }
                   13452:     }
                   13453:     return ($count,$datatable);
                   13454: }
                   13455: 
                   13456: sub recurse_extracted_archive {
1.1056    raeburn  13457:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13458:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13459:     my $result='';
1.1056    raeburn  13460:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13461:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13462:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13463:         return $result;
                   13464:     }
                   13465:     my $dirptr = 16384;
                   13466:     my ($newdirlistref,$newlisterror) =
                   13467:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13468:     if (ref($newdirlistref) eq 'ARRAY') {
                   13469:         foreach my $dir_line (@{$newdirlistref}) {
                   13470:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13471:             unless ($item =~ /^\.+$/) {
                   13472:                 $$count ++;
1.1056    raeburn  13473:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13474:                 $titles->{$$count} = $item;
1.1055    raeburn  13475:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13476: 
1.1055    raeburn  13477:                 my $is_dir;
                   13478:                 if ($dirptr&$testdir) {
                   13479:                     $is_dir = 1;
                   13480:                 }
                   13481:                 if ($wantform) {
                   13482:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13483:                 }
                   13484:                 if ($is_dir) {
                   13485:                     $$depth ++;
1.1056    raeburn  13486:                     push(@{$hierarchy},$$count);
                   13487:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13488:                     $result .=
                   13489:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13490:                                                    $docuname,$depth,$count,
1.1056    raeburn  13491:                                                    $hierarchy,$dirorder,$children,
                   13492:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13493:                     $$depth --;
1.1056    raeburn  13494:                     pop(@{$hierarchy});
1.1055    raeburn  13495:                 }
                   13496:             }
                   13497:         }
                   13498:     }
                   13499:     return $result;
                   13500: }
                   13501: 
                   13502: sub archive_hierarchy {
                   13503:     my ($depth,$count,$parent,$children) =@_;
                   13504:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13505:         if (exists($parent->{$depth})) {
                   13506:              $children->{$parent->{$depth}} .= $count.':';
                   13507:         }
                   13508:     }
                   13509:     return;
                   13510: }
                   13511: 
                   13512: sub archive_row {
                   13513:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13514:     my ($name) = ($item =~ m{([^/]+)$});
                   13515:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13516:                                        'display'    => 'Add as file',
1.1055    raeburn  13517:                                        'dependency' => 'Include as dependency',
                   13518:                                        'discard'    => 'Discard',
                   13519:                                       );
                   13520:     if ($is_dir) {
1.1059    raeburn  13521:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13522:     }
1.1056    raeburn  13523:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13524:     my $offset = 0;
1.1055    raeburn  13525:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13526:         $offset ++;
1.1065    raeburn  13527:         if ($action ne 'display') {
                   13528:             $offset ++;
                   13529:         }  
1.1055    raeburn  13530:         $output .= '<td><span class="LC_nobreak">'.
                   13531:                    '<label><input type="radio" name="archive_'.$count.
                   13532:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13533:         my $text = $choices{$action};
                   13534:         if ($is_dir) {
                   13535:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13536:             if ($action eq 'display') {
1.1059    raeburn  13537:                 $text = &mt('Add as folder');
1.1055    raeburn  13538:             }
1.1056    raeburn  13539:         } else {
                   13540:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13541: 
                   13542:         }
                   13543:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13544:         if ($action eq 'dependency') {
                   13545:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13546:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13547:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13548:                        '<option value=""></option>'."\n".
                   13549:                        '</select>'."\n".
                   13550:                        '</div>';
1.1059    raeburn  13551:         } elsif ($action eq 'display') {
                   13552:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13553:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13554:                        '</div>';
1.1055    raeburn  13555:         }
1.1056    raeburn  13556:         $output .= '</td>';
1.1055    raeburn  13557:     }
                   13558:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13559:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13560:     for (my $i=0; $i<$depth; $i++) {
                   13561:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13562:     }
                   13563:     if ($is_dir) {
                   13564:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13565:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13566:     } else {
                   13567:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13568:     }
                   13569:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13570:                &end_data_table_row();
                   13571:     return $output;
                   13572: }
                   13573: 
                   13574: sub archive_options_form {
1.1065    raeburn  13575:     my ($form,$display,$count,$hiddenelem) = @_;
                   13576:     my %lt = &Apache::lonlocal::texthash(
                   13577:                perm => 'Permanently remove archive file?',
                   13578:                hows => 'How should each extracted item be incorporated in the course?',
                   13579:                cont => 'Content actions for all',
                   13580:                addf => 'Add as folder/file',
                   13581:                incd => 'Include as dependency for a displayed file',
                   13582:                disc => 'Discard',
                   13583:                no   => 'No',
                   13584:                yes  => 'Yes',
                   13585:                save => 'Save',
                   13586:     );
                   13587:     my $output = <<"END";
                   13588: <form name="$form" method="post" action="">
                   13589: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13590: <label>
                   13591:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13592: </label>
                   13593: &nbsp;
                   13594: <label>
                   13595:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13596: </span>
                   13597: </p>
                   13598: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13599: <br />$lt{'hows'}
                   13600: <div class="LC_columnSection">
                   13601:   <fieldset>
                   13602:     <legend>$lt{'cont'}</legend>
                   13603:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13604:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13605:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13606:   </fieldset>
                   13607: </div>
                   13608: END
                   13609:     return $output.
1.1055    raeburn  13610:            &start_data_table()."\n".
1.1065    raeburn  13611:            $display."\n".
1.1055    raeburn  13612:            &end_data_table()."\n".
                   13613:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13614:            $hiddenelem.
1.1065    raeburn  13615:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13616:            '</form>';
                   13617: }
                   13618: 
                   13619: sub archive_javascript {
1.1056    raeburn  13620:     my ($startcount,$numitems,$titles,$children) = @_;
                   13621:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13622:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13623:     my $scripttag = <<START;
                   13624: <script type="text/javascript">
                   13625: // <![CDATA[
                   13626: 
                   13627: function checkAll(form,prefix) {
                   13628:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13629:     for (var i=0; i < form.elements.length; i++) {
                   13630:         var id = form.elements[i].id;
                   13631:         if ((id != '') && (id != undefined)) {
                   13632:             if (idstr.test(id)) {
                   13633:                 if (form.elements[i].type == 'radio') {
                   13634:                     form.elements[i].checked = true;
1.1056    raeburn  13635:                     var nostart = i-$startcount;
1.1059    raeburn  13636:                     var offset = nostart%7;
                   13637:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13638:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13639:                 }
                   13640:             }
                   13641:         }
                   13642:     }
                   13643: }
                   13644: 
                   13645: function propagateCheck(form,count) {
                   13646:     if (count > 0) {
1.1059    raeburn  13647:         var startelement = $startcount + ((count-1) * 7);
                   13648:         for (var j=1; j<6; j++) {
                   13649:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13650:                 var item = startelement + j; 
                   13651:                 if (form.elements[item].type == 'radio') {
                   13652:                     if (form.elements[item].checked) {
                   13653:                         containerCheck(form,count,j);
                   13654:                         break;
                   13655:                     }
1.1055    raeburn  13656:                 }
                   13657:             }
                   13658:         }
                   13659:     }
                   13660: }
                   13661: 
                   13662: numitems = $numitems
1.1056    raeburn  13663: var titles = new Array(numitems);
                   13664: var parents = new Array(numitems);
1.1055    raeburn  13665: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13666:     parents[i] = new Array;
1.1055    raeburn  13667: }
1.1059    raeburn  13668: var maintitle = '$maintitle';
1.1055    raeburn  13669: 
                   13670: START
                   13671: 
1.1056    raeburn  13672:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13673:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13674:         for (my $i=0; $i<@contents; $i ++) {
                   13675:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13676:         }
                   13677:     }
                   13678: 
1.1056    raeburn  13679:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13680:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13681:     }
                   13682: 
1.1055    raeburn  13683:     $scripttag .= <<END;
                   13684: 
                   13685: function containerCheck(form,count,offset) {
                   13686:     if (count > 0) {
1.1056    raeburn  13687:         dependencyCheck(form,count,offset);
1.1059    raeburn  13688:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13689:         form.elements[item].checked = true;
                   13690:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13691:             if (parents[count].length > 0) {
                   13692:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13693:                     containerCheck(form,parents[count][j],offset);
                   13694:                 }
                   13695:             }
                   13696:         }
                   13697:     }
                   13698: }
                   13699: 
                   13700: function dependencyCheck(form,count,offset) {
                   13701:     if (count > 0) {
1.1059    raeburn  13702:         var chosen = (offset+$startcount)+7*(count-1);
                   13703:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13704:         var currtype = form.elements[depitem].type;
                   13705:         if (form.elements[chosen].value == 'dependency') {
                   13706:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13707:             form.elements[depitem].options.length = 0;
                   13708:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13709:             for (var i=1; i<=numitems; i++) {
                   13710:                 if (i == count) {
                   13711:                     continue;
                   13712:                 }
1.1059    raeburn  13713:                 var startelement = $startcount + (i-1) * 7;
                   13714:                 for (var j=1; j<6; j++) {
                   13715:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13716:                         var item = startelement + j;
                   13717:                         if (form.elements[item].type == 'radio') {
                   13718:                             if (form.elements[item].checked) {
                   13719:                                 if (form.elements[item].value == 'display') {
                   13720:                                     var n = form.elements[depitem].options.length;
                   13721:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13722:                                 }
                   13723:                             }
                   13724:                         }
                   13725:                     }
                   13726:                 }
                   13727:             }
                   13728:         } else {
                   13729:             document.getElementById('arc_depon_'+count).style.display='none';
                   13730:             form.elements[depitem].options.length = 0;
                   13731:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13732:         }
1.1059    raeburn  13733:         titleCheck(form,count,offset);
1.1056    raeburn  13734:     }
                   13735: }
                   13736: 
                   13737: function propagateSelect(form,count,offset) {
                   13738:     if (count > 0) {
1.1065    raeburn  13739:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13740:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13741:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13742:             if (parents[count].length > 0) {
                   13743:                 for (var j=0; j<parents[count].length; j++) {
                   13744:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13745:                 }
                   13746:             }
                   13747:         }
                   13748:     }
                   13749: }
1.1056    raeburn  13750: 
                   13751: function containerSelect(form,count,offset,picked) {
                   13752:     if (count > 0) {
1.1065    raeburn  13753:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13754:         if (form.elements[item].type == 'radio') {
                   13755:             if (form.elements[item].value == 'dependency') {
                   13756:                 if (form.elements[item+1].type == 'select-one') {
                   13757:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13758:                         if (form.elements[item+1].options[i].value == picked) {
                   13759:                             form.elements[item+1].selectedIndex = i;
                   13760:                             break;
                   13761:                         }
                   13762:                     }
                   13763:                 }
                   13764:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13765:                     if (parents[count].length > 0) {
                   13766:                         for (var j=0; j<parents[count].length; j++) {
                   13767:                             containerSelect(form,parents[count][j],offset,picked);
                   13768:                         }
                   13769:                     }
                   13770:                 }
                   13771:             }
                   13772:         }
                   13773:     }
                   13774: }
                   13775: 
1.1059    raeburn  13776: function titleCheck(form,count,offset) {
                   13777:     if (count > 0) {
                   13778:         var chosen = (offset+$startcount)+7*(count-1);
                   13779:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13780:         var currtype = form.elements[depitem].type;
                   13781:         if (form.elements[chosen].value == 'display') {
                   13782:             document.getElementById('arc_title_'+count).style.display='block';
                   13783:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13784:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13785:             }
                   13786:         } else {
                   13787:             document.getElementById('arc_title_'+count).style.display='none';
                   13788:             if (currtype == 'text') { 
                   13789:                 document.getElementById('archive_title_'+count).value='';
                   13790:             }
                   13791:         }
                   13792:     }
                   13793:     return;
                   13794: }
                   13795: 
1.1055    raeburn  13796: // ]]>
                   13797: </script>
                   13798: END
                   13799:     return $scripttag;
                   13800: }
                   13801: 
                   13802: sub process_extracted_files {
1.1067    raeburn  13803:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13804:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13805:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13806:     my @ids=&Apache::lonnet::current_machine_ids();
                   13807:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13808:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13809:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13810:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13811:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13812:         $pathtocheck = "$dir_root/$destination";
                   13813:         $dir = $dir_root;
                   13814:         $ishome = 1;
                   13815:     } else {
                   13816:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13817:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13818:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13819:     }
                   13820:     my $currdir = "$dir_root/$destination";
                   13821:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13822:     if ($env{'form.folderpath'}) {
                   13823:         my @items = split('&',$env{'form.folderpath'});
                   13824:         $folders{'0'} = $items[-2];
1.1099    raeburn  13825:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13826:             $containers{'0'}='page';
                   13827:         } else {  
                   13828:             $containers{'0'}='sequence';
                   13829:         }
1.1055    raeburn  13830:     }
                   13831:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13832:     if ($numitems) {
                   13833:         for (my $i=1; $i<=$numitems; $i++) {
                   13834:             my $path = $env{'form.archive_content_'.$i};
                   13835:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13836:                 my $item = $1;
                   13837:                 $toplevelitems{$item} = $i;
                   13838:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13839:                     $is_dir{$item} = 1;
                   13840:                 }
                   13841:             }
                   13842:         }
                   13843:     }
1.1067    raeburn  13844:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13845:     if (keys(%toplevelitems) > 0) {
                   13846:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13847:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13848:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13849:     }
1.1066    raeburn  13850:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13851:     if ($numitems) {
                   13852:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13853:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13854:             my $path = $env{'form.archive_content_'.$i};
                   13855:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13856:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13857:                     if ($prefix ne '' && $path ne '') {
                   13858:                         if (-e $prefix.$path) {
1.1066    raeburn  13859:                             if ((@archdirs > 0) && 
                   13860:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13861:                                 $todeletedir{$prefix.$path} = 1;
                   13862:                             } else {
                   13863:                                 $todelete{$prefix.$path} = 1;
                   13864:                             }
1.1055    raeburn  13865:                         }
                   13866:                     }
                   13867:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13868:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13869:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13870:                     $docstitle = $env{'form.archive_title_'.$i};
                   13871:                     if ($docstitle eq '') {
                   13872:                         $docstitle = $title;
                   13873:                     }
1.1055    raeburn  13874:                     $outer = 0;
1.1056    raeburn  13875:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13876:                         if (@{$dirorder{$i}} > 0) {
                   13877:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13878:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13879:                                     $outer = $item;
                   13880:                                     last;
                   13881:                                 }
                   13882:                             }
                   13883:                         }
                   13884:                     }
                   13885:                     my ($errtext,$fatal) = 
                   13886:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13887:                                                '/'.$folders{$outer}.'.'.
                   13888:                                                $containers{$outer});
                   13889:                     next if ($fatal);
                   13890:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13891:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13892:                             $mapinner{$i} = time;
1.1055    raeburn  13893:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13894:                             $containers{$i} = 'sequence';
                   13895:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13896:                                       $folders{$i}.'.'.$containers{$i};
                   13897:                             my $newidx = &LONCAPA::map::getresidx();
                   13898:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13899:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13900:                             push(@LONCAPA::map::order,$newidx);
                   13901:                             my ($outtext,$errtext) =
                   13902:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13903:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13904:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13905:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13906:                             unless ($errtext) {
1.1294    raeburn  13907:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13908:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13909:                                             '</li>'."\n";
1.1067    raeburn  13910:                             }
1.1055    raeburn  13911:                         }
                   13912:                     } else {
                   13913:                         if ($context eq 'coursedocs') {
                   13914:                             my $newidx=&LONCAPA::map::getresidx();
                   13915:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13916:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13917:                                       $title;
1.1294    raeburn  13918:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13919:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13920:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13921:                                 }
                   13922:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13923:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13924:                                 }
                   13925:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13926:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13927:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13928:                                         unless ($ishome) {
                   13929:                                             my $fetch = "$newdest{$i}/$title";
                   13930:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13931:                                             $prompttofetch{$fetch} = 1;
                   13932:                                         }
1.1292    raeburn  13933:                                     }
1.1067    raeburn  13934:                                 }
1.1294    raeburn  13935:                                 $LONCAPA::map::resources[$newidx]=
                   13936:                                     $docstitle.':'.$url.':false:normal:res';
                   13937:                                 push(@LONCAPA::map::order, $newidx);
                   13938:                                 my ($outtext,$errtext)=
                   13939:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13940:                                                             $docuname.'/'.$folders{$outer}.
                   13941:                                                             '.'.$containers{$outer},1,1);
                   13942:                                 unless ($errtext) {
                   13943:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13944:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13945:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13946:                                                    '</li>'."\n";
                   13947:                                     }
1.1067    raeburn  13948:                                 }
1.1294    raeburn  13949:                             } else {
                   13950:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13951:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13952:                             }
1.1055    raeburn  13953:                         }
                   13954:                     }
1.1086    raeburn  13955:                 }
                   13956:             } else {
1.1294    raeburn  13957:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13958:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13959:             }
                   13960:         }
                   13961:         for (my $i=1; $i<=$numitems; $i++) {
                   13962:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13963:             my $path = $env{'form.archive_content_'.$i};
                   13964:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13965:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13966:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13967:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13968:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13969:                         my ($itemidx,$fullpath,$relpath);
                   13970:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13971:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13972:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13973:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13974:                                     $itemidx = $j;
1.1056    raeburn  13975:                                 }
                   13976:                             }
1.1086    raeburn  13977:                         }
                   13978:                         if ($itemidx eq '') {
                   13979:                             $itemidx =  0;
                   13980:                         } 
                   13981:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13982:                             if ($mapinner{$referrer{$i}}) {
                   13983:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13984:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13985:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13986:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13987:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13988:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13989:                                             if (!-e $fullpath) {
                   13990:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13991:                                             }
                   13992:                                         }
1.1086    raeburn  13993:                                     } else {
                   13994:                                         last;
1.1056    raeburn  13995:                                     }
1.1086    raeburn  13996:                                 }
                   13997:                             }
                   13998:                         } elsif ($newdest{$referrer{$i}}) {
                   13999:                             $fullpath = $newdest{$referrer{$i}};
                   14000:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14001:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14002:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14003:                                     last;
                   14004:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14005:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14006:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14007:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14008:                                         if (!-e $fullpath) {
                   14009:                                             mkdir($fullpath,0755);
1.1056    raeburn  14010:                                         }
                   14011:                                     }
1.1086    raeburn  14012:                                 } else {
                   14013:                                     last;
1.1056    raeburn  14014:                                 }
1.1055    raeburn  14015:                             }
                   14016:                         }
1.1086    raeburn  14017:                         if ($fullpath ne '') {
                   14018:                             if (-e "$prefix$path") {
1.1292    raeburn  14019:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14020:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14021:                                 }
1.1086    raeburn  14022:                             }
                   14023:                             if (-e "$fullpath/$title") {
                   14024:                                 my $showpath;
                   14025:                                 if ($relpath ne '') {
                   14026:                                     $showpath = "$relpath/$title";
                   14027:                                 } else {
                   14028:                                     $showpath = "/$title";
                   14029:                                 } 
1.1294    raeburn  14030:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14031:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14032:                                            '</li>'."\n";
1.1292    raeburn  14033:                                 unless ($ishome) {
                   14034:                                     my $fetch = "$fullpath/$title";
                   14035:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14036:                                     $prompttofetch{$fetch} = 1;
                   14037:                                 }
1.1086    raeburn  14038:                             }
                   14039:                         }
1.1055    raeburn  14040:                     }
1.1086    raeburn  14041:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14042:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14043:                                     &HTML::Entities::encode($path,'<>&"'),
                   14044:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14045:                                 '<br />';
1.1055    raeburn  14046:                 }
                   14047:             } else {
1.1294    raeburn  14048:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14049:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14050:             }
                   14051:         }
                   14052:         if (keys(%todelete)) {
                   14053:             foreach my $key (keys(%todelete)) {
                   14054:                 unlink($key);
1.1066    raeburn  14055:             }
                   14056:         }
                   14057:         if (keys(%todeletedir)) {
                   14058:             foreach my $key (keys(%todeletedir)) {
                   14059:                 rmdir($key);
                   14060:             }
                   14061:         }
                   14062:         foreach my $dir (sort(keys(%is_dir))) {
                   14063:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14064:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14065:             }
                   14066:         }
1.1067    raeburn  14067:         if ($result ne '') {
                   14068:             $output .= '<ul>'."\n".
                   14069:                        $result."\n".
                   14070:                        '</ul>';
                   14071:         }
                   14072:         unless ($ishome) {
                   14073:             my $replicationfail;
                   14074:             foreach my $item (keys(%prompttofetch)) {
                   14075:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14076:                 unless ($fetchresult eq 'ok') {
                   14077:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14078:                 }
                   14079:             }
                   14080:             if ($replicationfail) {
                   14081:                 $output .= '<p class="LC_error">'.
                   14082:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14083:                            $replicationfail.
                   14084:                            '</ul></p>';
                   14085:             }
                   14086:         }
1.1055    raeburn  14087:     } else {
                   14088:         $warning = &mt('No items found in archive.');
                   14089:     }
                   14090:     if ($error) {
                   14091:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14092:                    $error.'</p>'."\n";
                   14093:     }
                   14094:     if ($warning) {
                   14095:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14096:     }
                   14097:     return $output;
                   14098: }
                   14099: 
1.1066    raeburn  14100: sub cleanup_empty_dirs {
                   14101:     my ($path) = @_;
                   14102:     if (($path ne '') && (-d $path)) {
                   14103:         if (opendir(my $dirh,$path)) {
                   14104:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14105:             my $numitems = 0;
                   14106:             foreach my $item (@dircontents) {
                   14107:                 if (-d "$path/$item") {
1.1111    raeburn  14108:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14109:                     if (-e "$path/$item") {
                   14110:                         $numitems ++;
                   14111:                     }
                   14112:                 } else {
                   14113:                     $numitems ++;
                   14114:                 }
                   14115:             }
                   14116:             if ($numitems == 0) {
                   14117:                 rmdir($path);
                   14118:             }
                   14119:             closedir($dirh);
                   14120:         }
                   14121:     }
                   14122:     return;
                   14123: }
                   14124: 
1.41      ng       14125: =pod
1.45      matthew  14126: 
1.1162    raeburn  14127: =item * &get_folder_hierarchy()
1.1068    raeburn  14128: 
                   14129: Provides hierarchy of names of folders/sub-folders containing the current
                   14130: item,
                   14131: 
                   14132: Inputs: 3
                   14133:      - $navmap - navmaps object
                   14134: 
                   14135:      - $map - url for map (either the trigger itself, or map containing
                   14136:                            the resource, which is the trigger).
                   14137: 
                   14138:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14139: 
                   14140: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14141: 
                   14142: =cut
                   14143: 
                   14144: sub get_folder_hierarchy {
                   14145:     my ($navmap,$map,$showitem) = @_;
                   14146:     my @pathitems;
                   14147:     if (ref($navmap)) {
                   14148:         my $mapres = $navmap->getResourceByUrl($map);
                   14149:         if (ref($mapres)) {
                   14150:             my $pcslist = $mapres->map_hierarchy();
                   14151:             if ($pcslist ne '') {
                   14152:                 my @pcs = split(/,/,$pcslist);
                   14153:                 foreach my $pc (@pcs) {
                   14154:                     if ($pc == 1) {
1.1129    raeburn  14155:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14156:                     } else {
                   14157:                         my $res = $navmap->getByMapPc($pc);
                   14158:                         if (ref($res)) {
                   14159:                             my $title = $res->compTitle();
                   14160:                             $title =~ s/\W+/_/g;
                   14161:                             if ($title ne '') {
                   14162:                                 push(@pathitems,$title);
                   14163:                             }
                   14164:                         }
                   14165:                     }
                   14166:                 }
                   14167:             }
1.1071    raeburn  14168:             if ($showitem) {
                   14169:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14170:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14171:                 } else {
                   14172:                     my $maptitle = $mapres->compTitle();
                   14173:                     $maptitle =~ s/\W+/_/g;
                   14174:                     if ($maptitle ne '') {
                   14175:                         push(@pathitems,$maptitle);
                   14176:                     }
1.1068    raeburn  14177:                 }
                   14178:             }
                   14179:         }
                   14180:     }
                   14181:     return @pathitems;
                   14182: }
                   14183: 
                   14184: =pod
                   14185: 
1.1015    raeburn  14186: =item * &get_turnedin_filepath()
                   14187: 
                   14188: Determines path in a user's portfolio file for storage of files uploaded
                   14189: to a specific essayresponse or dropbox item.
                   14190: 
                   14191: Inputs: 3 required + 1 optional.
                   14192: $symb is symb for resource, $uname and $udom are for current user (required).
                   14193: $caller is optional (can be "submission", if routine is called when storing
                   14194: an upoaded file when "Submit Answer" button was pressed).
                   14195: 
                   14196: Returns array containing $path and $multiresp. 
                   14197: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14198: than one file upload item.  Callers of routine should append partid as a 
                   14199: subdirectory to $path in cases where $multiresp is 1.
                   14200: 
                   14201: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14202: 
                   14203: =cut
                   14204: 
                   14205: sub get_turnedin_filepath {
                   14206:     my ($symb,$uname,$udom,$caller) = @_;
                   14207:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14208:     my $turnindir;
                   14209:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14210:     $turnindir = $userhash{'turnindir'};
                   14211:     my ($path,$multiresp);
                   14212:     if ($turnindir eq '') {
                   14213:         if ($caller eq 'submission') {
                   14214:             $turnindir = &mt('turned in');
                   14215:             $turnindir =~ s/\W+/_/g;
                   14216:             my %newhash = (
                   14217:                             'turnindir' => $turnindir,
                   14218:                           );
                   14219:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14220:         }
                   14221:     }
                   14222:     if ($turnindir ne '') {
                   14223:         $path = '/'.$turnindir.'/';
                   14224:         my ($multipart,$turnin,@pathitems);
                   14225:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14226:         if (defined($navmap)) {
                   14227:             my $mapres = $navmap->getResourceByUrl($map);
                   14228:             if (ref($mapres)) {
                   14229:                 my $pcslist = $mapres->map_hierarchy();
                   14230:                 if ($pcslist ne '') {
                   14231:                     foreach my $pc (split(/,/,$pcslist)) {
                   14232:                         my $res = $navmap->getByMapPc($pc);
                   14233:                         if (ref($res)) {
                   14234:                             my $title = $res->compTitle();
                   14235:                             $title =~ s/\W+/_/g;
                   14236:                             if ($title ne '') {
1.1149    raeburn  14237:                                 if (($pc > 1) && (length($title) > 12)) {
                   14238:                                     $title = substr($title,0,12);
                   14239:                                 }
1.1015    raeburn  14240:                                 push(@pathitems,$title);
                   14241:                             }
                   14242:                         }
                   14243:                     }
                   14244:                 }
                   14245:                 my $maptitle = $mapres->compTitle();
                   14246:                 $maptitle =~ s/\W+/_/g;
                   14247:                 if ($maptitle ne '') {
1.1149    raeburn  14248:                     if (length($maptitle) > 12) {
                   14249:                         $maptitle = substr($maptitle,0,12);
                   14250:                     }
1.1015    raeburn  14251:                     push(@pathitems,$maptitle);
                   14252:                 }
                   14253:                 unless ($env{'request.state'} eq 'construct') {
                   14254:                     my $res = $navmap->getBySymb($symb);
                   14255:                     if (ref($res)) {
                   14256:                         my $partlist = $res->parts();
                   14257:                         my $totaluploads = 0;
                   14258:                         if (ref($partlist) eq 'ARRAY') {
                   14259:                             foreach my $part (@{$partlist}) {
                   14260:                                 my @types = $res->responseType($part);
                   14261:                                 my @ids = $res->responseIds($part);
                   14262:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14263:                                     if ($types[$i] eq 'essay') {
                   14264:                                         my $partid = $part.'_'.$ids[$i];
                   14265:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14266:                                             $totaluploads ++;
                   14267:                                         }
                   14268:                                     }
                   14269:                                 }
                   14270:                             }
                   14271:                             if ($totaluploads > 1) {
                   14272:                                 $multiresp = 1;
                   14273:                             }
                   14274:                         }
                   14275:                     }
                   14276:                 }
                   14277:             } else {
                   14278:                 return;
                   14279:             }
                   14280:         } else {
                   14281:             return;
                   14282:         }
                   14283:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14284:         $restitle =~ s/\W+/_/g;
                   14285:         if ($restitle eq '') {
                   14286:             $restitle = ($resurl =~ m{/[^/]+$});
                   14287:             if ($restitle eq '') {
                   14288:                 $restitle = time;
                   14289:             }
                   14290:         }
1.1149    raeburn  14291:         if (length($restitle) > 12) {
                   14292:             $restitle = substr($restitle,0,12);
                   14293:         }
1.1015    raeburn  14294:         push(@pathitems,$restitle);
                   14295:         $path .= join('/',@pathitems);
                   14296:     }
                   14297:     return ($path,$multiresp);
                   14298: }
                   14299: 
                   14300: =pod
                   14301: 
1.464     albertel 14302: =back
1.41      ng       14303: 
1.112     bowersj2 14304: =head1 CSV Upload/Handling functions
1.38      albertel 14305: 
1.41      ng       14306: =over 4
                   14307: 
1.648     raeburn  14308: =item * &upfile_store($r)
1.41      ng       14309: 
                   14310: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14311: needs $env{'form.upfile'}
1.41      ng       14312: returns $datatoken to be put into hidden field
                   14313: 
                   14314: =cut
1.31      albertel 14315: 
                   14316: sub upfile_store {
                   14317:     my $r=shift;
1.258     albertel 14318:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14319:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14320:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14321:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14322: 
1.1299    raeburn  14323:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14324:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14325:                                      time.'_'.$$);
                   14326:     return if ($datatoken eq '');
                   14327: 
1.31      albertel 14328:     {
1.158     raeburn  14329:         my $datafile = $r->dir_config('lonDaemons').
                   14330:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14331:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14332:             print $fh $env{'form.upfile'};
1.158     raeburn  14333:             close($fh);
                   14334:         }
1.31      albertel 14335:     }
                   14336:     return $datatoken;
                   14337: }
                   14338: 
1.56      matthew  14339: =pod
                   14340: 
1.1290    raeburn  14341: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14342: 
                   14343: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14344: $datatoken is the name to assign to the temporary file.
1.258     albertel 14345: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14346: 
                   14347: =cut
1.31      albertel 14348: 
                   14349: sub load_tmp_file {
1.1290    raeburn  14350:     my ($r,$datatoken) = @_;
                   14351:     return if ($datatoken eq '');
1.31      albertel 14352:     my @studentdata=();
                   14353:     {
1.158     raeburn  14354:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14355:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14356:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14357:             @studentdata=<$fh>;
                   14358:             close($fh);
                   14359:         }
1.31      albertel 14360:     }
1.258     albertel 14361:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14362: }
                   14363: 
1.1290    raeburn  14364: sub valid_datatoken {
                   14365:     my ($datatoken) = @_;
1.1325    raeburn  14366:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14367:         return $datatoken;
                   14368:     }
                   14369:     return;
                   14370: }
                   14371: 
1.56      matthew  14372: =pod
                   14373: 
1.648     raeburn  14374: =item * &upfile_record_sep()
1.41      ng       14375: 
                   14376: Separate uploaded file into records
                   14377: returns array of records,
1.258     albertel 14378: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14379: 
                   14380: =cut
1.31      albertel 14381: 
                   14382: sub upfile_record_sep {
1.258     albertel 14383:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14384:     } else {
1.248     albertel 14385: 	my @records;
1.258     albertel 14386: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14387: 	    if ($line=~/^\s*$/) { next; }
                   14388: 	    push(@records,$line);
                   14389: 	}
                   14390: 	return @records;
1.31      albertel 14391:     }
                   14392: }
                   14393: 
1.56      matthew  14394: =pod
                   14395: 
1.648     raeburn  14396: =item * &record_sep($record)
1.41      ng       14397: 
1.258     albertel 14398: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14399: 
                   14400: =cut
                   14401: 
1.263     www      14402: sub takeleft {
                   14403:     my $index=shift;
                   14404:     return substr('0000'.$index,-4,4);
                   14405: }
                   14406: 
1.31      albertel 14407: sub record_sep {
                   14408:     my $record=shift;
                   14409:     my %components=();
1.258     albertel 14410:     if ($env{'form.upfiletype'} eq 'xml') {
                   14411:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14412:         my $i=0;
1.356     albertel 14413:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14414:             $field=~s/^(\"|\')//;
                   14415:             $field=~s/(\"|\')$//;
1.263     www      14416:             $components{&takeleft($i)}=$field;
1.31      albertel 14417:             $i++;
                   14418:         }
1.258     albertel 14419:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14420:         my $i=0;
1.356     albertel 14421:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14422:             $field=~s/^(\"|\')//;
                   14423:             $field=~s/(\"|\')$//;
1.263     www      14424:             $components{&takeleft($i)}=$field;
1.31      albertel 14425:             $i++;
                   14426:         }
                   14427:     } else {
1.561     www      14428:         my $separator=',';
1.480     banghart 14429:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14430:             $separator=';';
1.480     banghart 14431:         }
1.31      albertel 14432:         my $i=0;
1.561     www      14433: # the character we are looking for to indicate the end of a quote or a record 
                   14434:         my $looking_for=$separator;
                   14435: # do not add the characters to the fields
                   14436:         my $ignore=0;
                   14437: # we just encountered a separator (or the beginning of the record)
                   14438:         my $just_found_separator=1;
                   14439: # store the field we are working on here
                   14440:         my $field='';
                   14441: # work our way through all characters in record
                   14442:         foreach my $character ($record=~/(.)/g) {
                   14443:             if ($character eq $looking_for) {
                   14444:                if ($character ne $separator) {
                   14445: # Found the end of a quote, again looking for separator
                   14446:                   $looking_for=$separator;
                   14447:                   $ignore=1;
                   14448:                } else {
                   14449: # Found a separator, store away what we got
                   14450:                   $components{&takeleft($i)}=$field;
                   14451: 	          $i++;
                   14452:                   $just_found_separator=1;
                   14453:                   $ignore=0;
                   14454:                   $field='';
                   14455:                }
                   14456:                next;
                   14457:             }
                   14458: # single or double quotation marks after a separator indicate beginning of a quote
                   14459: # we are now looking for the end of the quote and need to ignore separators
                   14460:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14461:                $looking_for=$character;
                   14462:                next;
                   14463:             }
                   14464: # ignore would be true after we reached the end of a quote
                   14465:             if ($ignore) { next; }
                   14466:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14467:             $field.=$character;
                   14468:             $just_found_separator=0; 
1.31      albertel 14469:         }
1.561     www      14470: # catch the very last entry, since we never encountered the separator
                   14471:         $components{&takeleft($i)}=$field;
1.31      albertel 14472:     }
                   14473:     return %components;
                   14474: }
                   14475: 
1.144     matthew  14476: ######################################################
                   14477: ######################################################
                   14478: 
1.56      matthew  14479: =pod
                   14480: 
1.648     raeburn  14481: =item * &upfile_select_html()
1.41      ng       14482: 
1.144     matthew  14483: Return HTML code to select a file from the users machine and specify 
                   14484: the file type.
1.41      ng       14485: 
                   14486: =cut
                   14487: 
1.144     matthew  14488: ######################################################
                   14489: ######################################################
1.31      albertel 14490: sub upfile_select_html {
1.144     matthew  14491:     my %Types = (
                   14492:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14493:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14494:                  space => &mt('Space separated'),
                   14495:                  tab   => &mt('Tabulator separated'),
                   14496: #                 xml   => &mt('HTML/XML'),
                   14497:                  );
                   14498:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14499:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14500:     foreach my $type (sort(keys(%Types))) {
                   14501:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14502:     }
                   14503:     $Str .= "</select>\n";
                   14504:     return $Str;
1.31      albertel 14505: }
                   14506: 
1.301     albertel 14507: sub get_samples {
                   14508:     my ($records,$toget) = @_;
                   14509:     my @samples=({});
                   14510:     my $got=0;
                   14511:     foreach my $rec (@$records) {
                   14512: 	my %temp = &record_sep($rec);
                   14513: 	if (! grep(/\S/, values(%temp))) { next; }
                   14514: 	if (%temp) {
                   14515: 	    $samples[$got]=\%temp;
                   14516: 	    $got++;
                   14517: 	    if ($got == $toget) { last; }
                   14518: 	}
                   14519:     }
                   14520:     return \@samples;
                   14521: }
                   14522: 
1.144     matthew  14523: ######################################################
                   14524: ######################################################
                   14525: 
1.56      matthew  14526: =pod
                   14527: 
1.648     raeburn  14528: =item * &csv_print_samples($r,$records)
1.41      ng       14529: 
                   14530: Prints a table of sample values from each column uploaded $r is an
                   14531: Apache Request ref, $records is an arrayref from
                   14532: &Apache::loncommon::upfile_record_sep
                   14533: 
                   14534: =cut
                   14535: 
1.144     matthew  14536: ######################################################
                   14537: ######################################################
1.31      albertel 14538: sub csv_print_samples {
                   14539:     my ($r,$records) = @_;
1.662     bisitz   14540:     my $samples = &get_samples($records,5);
1.301     albertel 14541: 
1.594     raeburn  14542:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14543:               &start_data_table_header_row());
1.356     albertel 14544:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14545:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14546:     $r->print(&end_data_table_header_row());
1.301     albertel 14547:     foreach my $hash (@$samples) {
1.594     raeburn  14548: 	$r->print(&start_data_table_row());
1.356     albertel 14549: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14550: 	    $r->print('<td>');
1.356     albertel 14551: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14552: 	    $r->print('</td>');
                   14553: 	}
1.594     raeburn  14554: 	$r->print(&end_data_table_row());
1.31      albertel 14555:     }
1.594     raeburn  14556:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14557: }
                   14558: 
1.144     matthew  14559: ######################################################
                   14560: ######################################################
                   14561: 
1.56      matthew  14562: =pod
                   14563: 
1.648     raeburn  14564: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14565: 
                   14566: Prints a table to create associations between values and table columns.
1.144     matthew  14567: 
1.41      ng       14568: $r is an Apache Request ref,
                   14569: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14570: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14571: 
                   14572: =cut
                   14573: 
1.144     matthew  14574: ######################################################
                   14575: ######################################################
1.31      albertel 14576: sub csv_print_select_table {
                   14577:     my ($r,$records,$d) = @_;
1.301     albertel 14578:     my $i=0;
                   14579:     my $samples = &get_samples($records,1);
1.144     matthew  14580:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14581: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14582:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14583:               '<th>'.&mt('Column').'</th>'.
                   14584:               &end_data_table_header_row()."\n");
1.356     albertel 14585:     foreach my $array_ref (@$d) {
                   14586: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14587: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14588: 
1.875     bisitz   14589: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14590: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14591: 	$r->print('<option value="none"></option>');
1.356     albertel 14592: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14593: 	    $r->print('<option value="'.$sample.'"'.
                   14594:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14595:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14596: 	}
1.594     raeburn  14597: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14598: 	$i++;
                   14599:     }
1.594     raeburn  14600:     $r->print(&end_data_table());
1.31      albertel 14601:     $i--;
                   14602:     return $i;
                   14603: }
1.56      matthew  14604: 
1.144     matthew  14605: ######################################################
                   14606: ######################################################
                   14607: 
1.56      matthew  14608: =pod
1.31      albertel 14609: 
1.648     raeburn  14610: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14611: 
                   14612: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14613: 
                   14614: $r is an Apache Request ref,
                   14615: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14616: $d is an array of 2 element arrays (internal name, displayed name)
                   14617: 
                   14618: =cut
                   14619: 
1.144     matthew  14620: ######################################################
                   14621: ######################################################
1.31      albertel 14622: sub csv_samples_select_table {
                   14623:     my ($r,$records,$d) = @_;
                   14624:     my $i=0;
1.144     matthew  14625:     #
1.662     bisitz   14626:     my $max_samples = 5;
                   14627:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14628:     $r->print(&start_data_table().
                   14629:               &start_data_table_header_row().'<th>'.
                   14630:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14631:               &end_data_table_header_row());
1.301     albertel 14632: 
                   14633:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14634: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14635: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14636: 	foreach my $option (@$d) {
                   14637: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14638: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14639:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14640:                       $display.'</option>');
1.31      albertel 14641: 	}
                   14642: 	$r->print('</select></td><td>');
1.662     bisitz   14643: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14644: 	    if (defined($samples->[$line]{$key})) { 
                   14645: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14646: 	    }
                   14647: 	}
1.594     raeburn  14648: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14649: 	$i++;
                   14650:     }
1.594     raeburn  14651:     $r->print(&end_data_table());
1.31      albertel 14652:     $i--;
                   14653:     return($i);
1.115     matthew  14654: }
                   14655: 
1.144     matthew  14656: ######################################################
                   14657: ######################################################
                   14658: 
1.115     matthew  14659: =pod
                   14660: 
1.648     raeburn  14661: =item * &clean_excel_name($name)
1.115     matthew  14662: 
                   14663: Returns a replacement for $name which does not contain any illegal characters.
                   14664: 
                   14665: =cut
                   14666: 
1.144     matthew  14667: ######################################################
                   14668: ######################################################
1.115     matthew  14669: sub clean_excel_name {
                   14670:     my ($name) = @_;
                   14671:     $name =~ s/[:\*\?\/\\]//g;
                   14672:     if (length($name) > 31) {
                   14673:         $name = substr($name,0,31);
                   14674:     }
                   14675:     return $name;
1.25      albertel 14676: }
1.84      albertel 14677: 
1.85      albertel 14678: =pod
                   14679: 
1.648     raeburn  14680: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14681: 
                   14682: Returns either 1 or undef
                   14683: 
                   14684: 1 if the part is to be hidden, undef if it is to be shown
                   14685: 
                   14686: Arguments are:
                   14687: 
                   14688: $id the id of the part to be checked
                   14689: $symb, optional the symb of the resource to check
                   14690: $udom, optional the domain of the user to check for
                   14691: $uname, optional the username of the user to check for
                   14692: 
                   14693: =cut
1.84      albertel 14694: 
                   14695: sub check_if_partid_hidden {
                   14696:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14697:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14698: 					 $symb,$udom,$uname);
1.141     albertel 14699:     my $truth=1;
                   14700:     #if the string starts with !, then the list is the list to show not hide
                   14701:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14702:     my @hiddenlist=split(/,/,$hiddenparts);
                   14703:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14704: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14705:     }
1.141     albertel 14706:     return !$truth;
1.84      albertel 14707: }
1.127     matthew  14708: 
1.138     matthew  14709: 
                   14710: ############################################################
                   14711: ############################################################
                   14712: 
                   14713: =pod
                   14714: 
1.157     matthew  14715: =back 
                   14716: 
1.138     matthew  14717: =head1 cgi-bin script and graphing routines
                   14718: 
1.157     matthew  14719: =over 4
                   14720: 
1.648     raeburn  14721: =item * &get_cgi_id()
1.138     matthew  14722: 
                   14723: Inputs: none
                   14724: 
                   14725: Returns an id which can be used to pass environment variables
                   14726: to various cgi-bin scripts.  These environment variables will
                   14727: be removed from the users environment after a given time by
                   14728: the routine &Apache::lonnet::transfer_profile_to_env.
                   14729: 
                   14730: =cut
                   14731: 
                   14732: ############################################################
                   14733: ############################################################
1.152     albertel 14734: my $uniq=0;
1.136     matthew  14735: sub get_cgi_id {
1.154     albertel 14736:     $uniq=($uniq+1)%100000;
1.280     albertel 14737:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14738: }
                   14739: 
1.127     matthew  14740: ############################################################
                   14741: ############################################################
                   14742: 
                   14743: =pod
                   14744: 
1.648     raeburn  14745: =item * &DrawBarGraph()
1.127     matthew  14746: 
1.138     matthew  14747: Facilitates the plotting of data in a (stacked) bar graph.
                   14748: Puts plot definition data into the users environment in order for 
                   14749: graph.png to plot it.  Returns an <img> tag for the plot.
                   14750: The bars on the plot are labeled '1','2',...,'n'.
                   14751: 
                   14752: Inputs:
                   14753: 
                   14754: =over 4
                   14755: 
                   14756: =item $Title: string, the title of the plot
                   14757: 
                   14758: =item $xlabel: string, text describing the X-axis of the plot
                   14759: 
                   14760: =item $ylabel: string, text describing the Y-axis of the plot
                   14761: 
                   14762: =item $Max: scalar, the maximum Y value to use in the plot
                   14763: If $Max is < any data point, the graph will not be rendered.
                   14764: 
1.140     matthew  14765: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14766: they are plotted.  If undefined, default values will be used.
                   14767: 
1.178     matthew  14768: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14769: 
1.138     matthew  14770: =item @Values: An array of array references.  Each array reference holds data
                   14771: to be plotted in a stacked bar chart.
                   14772: 
1.239     matthew  14773: =item If the final element of @Values is a hash reference the key/value
                   14774: pairs will be added to the graph definition.
                   14775: 
1.138     matthew  14776: =back
                   14777: 
                   14778: Returns:
                   14779: 
                   14780: An <img> tag which references graph.png and the appropriate identifying
                   14781: information for the plot.
                   14782: 
1.127     matthew  14783: =cut
                   14784: 
                   14785: ############################################################
                   14786: ############################################################
1.134     matthew  14787: sub DrawBarGraph {
1.178     matthew  14788:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14789:     #
                   14790:     if (! defined($colors)) {
                   14791:         $colors = ['#33ff00', 
                   14792:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14793:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14794:                   ]; 
                   14795:     }
1.228     matthew  14796:     my $extra_settings = {};
                   14797:     if (ref($Values[-1]) eq 'HASH') {
                   14798:         $extra_settings = pop(@Values);
                   14799:     }
1.127     matthew  14800:     #
1.136     matthew  14801:     my $identifier = &get_cgi_id();
                   14802:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14803:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14804:         return '';
                   14805:     }
1.225     matthew  14806:     #
                   14807:     my @Labels;
                   14808:     if (defined($labels)) {
                   14809:         @Labels = @$labels;
                   14810:     } else {
                   14811:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14812:             push(@Labels,$i+1);
1.225     matthew  14813:         }
                   14814:     }
                   14815:     #
1.129     matthew  14816:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14817:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14818:     my %ValuesHash;
                   14819:     my $NumSets=1;
                   14820:     foreach my $array (@Values) {
                   14821:         next if (! ref($array));
1.136     matthew  14822:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14823:             join(',',@$array);
1.129     matthew  14824:     }
1.127     matthew  14825:     #
1.136     matthew  14826:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14827:     if ($NumBars < 3) {
                   14828:         $width = 120+$NumBars*32;
1.220     matthew  14829:         $xskip = 1;
1.225     matthew  14830:         $bar_width = 30;
                   14831:     } elsif ($NumBars < 5) {
                   14832:         $width = 120+$NumBars*20;
                   14833:         $xskip = 1;
                   14834:         $bar_width = 20;
1.220     matthew  14835:     } elsif ($NumBars < 10) {
1.136     matthew  14836:         $width = 120+$NumBars*15;
                   14837:         $xskip = 1;
                   14838:         $bar_width = 15;
                   14839:     } elsif ($NumBars <= 25) {
                   14840:         $width = 120+$NumBars*11;
                   14841:         $xskip = 5;
                   14842:         $bar_width = 8;
                   14843:     } elsif ($NumBars <= 50) {
                   14844:         $width = 120+$NumBars*8;
                   14845:         $xskip = 5;
                   14846:         $bar_width = 4;
                   14847:     } else {
                   14848:         $width = 120+$NumBars*8;
                   14849:         $xskip = 5;
                   14850:         $bar_width = 4;
                   14851:     }
                   14852:     #
1.137     matthew  14853:     $Max = 1 if ($Max < 1);
                   14854:     if ( int($Max) < $Max ) {
                   14855:         $Max++;
                   14856:         $Max = int($Max);
                   14857:     }
1.127     matthew  14858:     $Title  = '' if (! defined($Title));
                   14859:     $xlabel = '' if (! defined($xlabel));
                   14860:     $ylabel = '' if (! defined($ylabel));
1.369     www      14861:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14862:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14863:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14864:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14865:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14866:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14867:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14868:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14869:     $ValuesHash{$id.'.height'}   = $height;
                   14870:     $ValuesHash{$id.'.width'}    = $width;
                   14871:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14872:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14873:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14874:     #
1.228     matthew  14875:     # Deal with other parameters
                   14876:     while (my ($key,$value) = each(%$extra_settings)) {
                   14877:         $ValuesHash{$id.'.'.$key} = $value;
                   14878:     }
                   14879:     #
1.646     raeburn  14880:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14881:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14882: }
                   14883: 
                   14884: ############################################################
                   14885: ############################################################
                   14886: 
                   14887: =pod
                   14888: 
1.648     raeburn  14889: =item * &DrawXYGraph()
1.137     matthew  14890: 
1.138     matthew  14891: Facilitates the plotting of data in an XY graph.
                   14892: Puts plot definition data into the users environment in order for 
                   14893: graph.png to plot it.  Returns an <img> tag for the plot.
                   14894: 
                   14895: Inputs:
                   14896: 
                   14897: =over 4
                   14898: 
                   14899: =item $Title: string, the title of the plot
                   14900: 
                   14901: =item $xlabel: string, text describing the X-axis of the plot
                   14902: 
                   14903: =item $ylabel: string, text describing the Y-axis of the plot
                   14904: 
                   14905: =item $Max: scalar, the maximum Y value to use in the plot
                   14906: If $Max is < any data point, the graph will not be rendered.
                   14907: 
                   14908: =item $colors: Array ref containing the hex color codes for the data to be 
                   14909: plotted in.  If undefined, default values will be used.
                   14910: 
                   14911: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14912: 
                   14913: =item $Ydata: Array ref containing Array refs.  
1.185     www      14914: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14915: 
                   14916: =item %Values: hash indicating or overriding any default values which are 
                   14917: passed to graph.png.  
                   14918: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14919: 
                   14920: =back
                   14921: 
                   14922: Returns:
                   14923: 
                   14924: An <img> tag which references graph.png and the appropriate identifying
                   14925: information for the plot.
                   14926: 
1.137     matthew  14927: =cut
                   14928: 
                   14929: ############################################################
                   14930: ############################################################
                   14931: sub DrawXYGraph {
                   14932:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14933:     #
                   14934:     # Create the identifier for the graph
                   14935:     my $identifier = &get_cgi_id();
                   14936:     my $id = 'cgi.'.$identifier;
                   14937:     #
                   14938:     $Title  = '' if (! defined($Title));
                   14939:     $xlabel = '' if (! defined($xlabel));
                   14940:     $ylabel = '' if (! defined($ylabel));
                   14941:     my %ValuesHash = 
                   14942:         (
1.369     www      14943:          $id.'.title'  => &escape($Title),
                   14944:          $id.'.xlabel' => &escape($xlabel),
                   14945:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14946:          $id.'.y_max_value'=> $Max,
                   14947:          $id.'.labels'     => join(',',@$Xlabels),
                   14948:          $id.'.PlotType'   => 'XY',
                   14949:          );
                   14950:     #
                   14951:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14952:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14953:     }
                   14954:     #
                   14955:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14956:         return '';
                   14957:     }
                   14958:     my $NumSets=1;
1.138     matthew  14959:     foreach my $array (@{$Ydata}){
1.137     matthew  14960:         next if (! ref($array));
                   14961:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14962:     }
1.138     matthew  14963:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14964:     #
                   14965:     # Deal with other parameters
                   14966:     while (my ($key,$value) = each(%Values)) {
                   14967:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14968:     }
                   14969:     #
1.646     raeburn  14970:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14971:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14972: }
                   14973: 
                   14974: ############################################################
                   14975: ############################################################
                   14976: 
                   14977: =pod
                   14978: 
1.648     raeburn  14979: =item * &DrawXYYGraph()
1.138     matthew  14980: 
                   14981: Facilitates the plotting of data in an XY graph with two Y axes.
                   14982: Puts plot definition data into the users environment in order for 
                   14983: graph.png to plot it.  Returns an <img> tag for the plot.
                   14984: 
                   14985: Inputs:
                   14986: 
                   14987: =over 4
                   14988: 
                   14989: =item $Title: string, the title of the plot
                   14990: 
                   14991: =item $xlabel: string, text describing the X-axis of the plot
                   14992: 
                   14993: =item $ylabel: string, text describing the Y-axis of the plot
                   14994: 
                   14995: =item $colors: Array ref containing the hex color codes for the data to be 
                   14996: plotted in.  If undefined, default values will be used.
                   14997: 
                   14998: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14999: 
                   15000: =item $Ydata1: The first data set
                   15001: 
                   15002: =item $Min1: The minimum value of the left Y-axis
                   15003: 
                   15004: =item $Max1: The maximum value of the left Y-axis
                   15005: 
                   15006: =item $Ydata2: The second data set
                   15007: 
                   15008: =item $Min2: The minimum value of the right Y-axis
                   15009: 
                   15010: =item $Max2: The maximum value of the left Y-axis
                   15011: 
                   15012: =item %Values: hash indicating or overriding any default values which are 
                   15013: passed to graph.png.  
                   15014: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15015: 
                   15016: =back
                   15017: 
                   15018: Returns:
                   15019: 
                   15020: An <img> tag which references graph.png and the appropriate identifying
                   15021: information for the plot.
1.136     matthew  15022: 
                   15023: =cut
                   15024: 
                   15025: ############################################################
                   15026: ############################################################
1.137     matthew  15027: sub DrawXYYGraph {
                   15028:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15029:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15030:     #
                   15031:     # Create the identifier for the graph
                   15032:     my $identifier = &get_cgi_id();
                   15033:     my $id = 'cgi.'.$identifier;
                   15034:     #
                   15035:     $Title  = '' if (! defined($Title));
                   15036:     $xlabel = '' if (! defined($xlabel));
                   15037:     $ylabel = '' if (! defined($ylabel));
                   15038:     my %ValuesHash = 
                   15039:         (
1.369     www      15040:          $id.'.title'  => &escape($Title),
                   15041:          $id.'.xlabel' => &escape($xlabel),
                   15042:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15043:          $id.'.labels' => join(',',@$Xlabels),
                   15044:          $id.'.PlotType' => 'XY',
                   15045:          $id.'.NumSets' => 2,
1.137     matthew  15046:          $id.'.two_axes' => 1,
                   15047:          $id.'.y1_max_value' => $Max1,
                   15048:          $id.'.y1_min_value' => $Min1,
                   15049:          $id.'.y2_max_value' => $Max2,
                   15050:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15051:          );
                   15052:     #
1.137     matthew  15053:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15054:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15055:     }
                   15056:     #
                   15057:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15058:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15059:         return '';
                   15060:     }
                   15061:     my $NumSets=1;
1.137     matthew  15062:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15063:         next if (! ref($array));
                   15064:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15065:     }
                   15066:     #
                   15067:     # Deal with other parameters
                   15068:     while (my ($key,$value) = each(%Values)) {
                   15069:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15070:     }
                   15071:     #
1.646     raeburn  15072:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15073:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15074: }
                   15075: 
                   15076: ############################################################
                   15077: ############################################################
                   15078: 
                   15079: =pod
                   15080: 
1.157     matthew  15081: =back 
                   15082: 
1.139     matthew  15083: =head1 Statistics helper routines?  
                   15084: 
                   15085: Bad place for them but what the hell.
                   15086: 
1.157     matthew  15087: =over 4
                   15088: 
1.648     raeburn  15089: =item * &chartlink()
1.139     matthew  15090: 
                   15091: Returns a link to the chart for a specific student.  
                   15092: 
                   15093: Inputs:
                   15094: 
                   15095: =over 4
                   15096: 
                   15097: =item $linktext: The text of the link
                   15098: 
                   15099: =item $sname: The students username
                   15100: 
                   15101: =item $sdomain: The students domain
                   15102: 
                   15103: =back
                   15104: 
1.157     matthew  15105: =back
                   15106: 
1.139     matthew  15107: =cut
                   15108: 
                   15109: ############################################################
                   15110: ############################################################
                   15111: sub chartlink {
                   15112:     my ($linktext, $sname, $sdomain) = @_;
                   15113:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15114:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15115:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15116:        '">'.$linktext.'</a>';
1.153     matthew  15117: }
                   15118: 
                   15119: #######################################################
                   15120: #######################################################
                   15121: 
                   15122: =pod
                   15123: 
                   15124: =head1 Course Environment Routines
1.157     matthew  15125: 
                   15126: =over 4
1.153     matthew  15127: 
1.648     raeburn  15128: =item * &restore_course_settings()
1.153     matthew  15129: 
1.648     raeburn  15130: =item * &store_course_settings()
1.153     matthew  15131: 
                   15132: Restores/Store indicated form parameters from the course environment.
                   15133: Will not overwrite existing values of the form parameters.
                   15134: 
                   15135: Inputs: 
                   15136: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15137: 
                   15138: a hash ref describing the data to be stored.  For example:
                   15139:    
                   15140: %Save_Parameters = ('Status' => 'scalar',
                   15141:     'chartoutputmode' => 'scalar',
                   15142:     'chartoutputdata' => 'scalar',
                   15143:     'Section' => 'array',
1.373     raeburn  15144:     'Group' => 'array',
1.153     matthew  15145:     'StudentData' => 'array',
                   15146:     'Maps' => 'array');
                   15147: 
                   15148: Returns: both routines return nothing
                   15149: 
1.631     raeburn  15150: =back
                   15151: 
1.153     matthew  15152: =cut
                   15153: 
                   15154: #######################################################
                   15155: #######################################################
                   15156: sub store_course_settings {
1.496     albertel 15157:     return &store_settings($env{'request.course.id'},@_);
                   15158: }
                   15159: 
                   15160: sub store_settings {
1.153     matthew  15161:     # save to the environment
                   15162:     # appenv the same items, just to be safe
1.300     albertel 15163:     my $udom  = $env{'user.domain'};
                   15164:     my $uname = $env{'user.name'};
1.496     albertel 15165:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15166:     my %SaveHash;
                   15167:     my %AppHash;
                   15168:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15169:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15170:         my $envname = 'environment.'.$basename;
1.258     albertel 15171:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15172:             # Save this value away
                   15173:             if ($type eq 'scalar' &&
1.258     albertel 15174:                 (! exists($env{$envname}) || 
                   15175:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15176:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15177:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15178:             } elsif ($type eq 'array') {
                   15179:                 my $stored_form;
1.258     albertel 15180:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15181:                     $stored_form = join(',',
                   15182:                                         map {
1.369     www      15183:                                             &escape($_);
1.258     albertel 15184:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15185:                 } else {
                   15186:                     $stored_form = 
1.369     www      15187:                         &escape($env{'form.'.$setting});
1.153     matthew  15188:                 }
                   15189:                 # Determine if the array contents are the same.
1.258     albertel 15190:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15191:                     $SaveHash{$basename} = $stored_form;
                   15192:                     $AppHash{$envname}   = $stored_form;
                   15193:                 }
                   15194:             }
                   15195:         }
                   15196:     }
                   15197:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15198:                                           $udom,$uname);
1.153     matthew  15199:     if ($put_result !~ /^(ok|delayed)/) {
                   15200:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15201:                                  'got error:'.$put_result);
                   15202:     }
                   15203:     # Make sure these settings stick around in this session, too
1.646     raeburn  15204:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15205:     return;
                   15206: }
                   15207: 
                   15208: sub restore_course_settings {
1.499     albertel 15209:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15210: }
                   15211: 
                   15212: sub restore_settings {
                   15213:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15214:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15215:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15216:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15217:             '.'.$setting;
1.258     albertel 15218:         if (exists($env{$envname})) {
1.153     matthew  15219:             if ($type eq 'scalar') {
1.258     albertel 15220:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15221:             } elsif ($type eq 'array') {
1.258     albertel 15222:                 $env{'form.'.$setting} = [ 
1.153     matthew  15223:                                            map { 
1.369     www      15224:                                                &unescape($_); 
1.258     albertel 15225:                                            } split(',',$env{$envname})
1.153     matthew  15226:                                            ];
                   15227:             }
                   15228:         }
                   15229:     }
1.127     matthew  15230: }
                   15231: 
1.618     raeburn  15232: #######################################################
                   15233: #######################################################
                   15234: 
                   15235: =pod
                   15236: 
                   15237: =head1 Domain E-mail Routines  
                   15238: 
                   15239: =over 4
                   15240: 
1.648     raeburn  15241: =item * &build_recipient_list()
1.618     raeburn  15242: 
1.1144    raeburn  15243: Build recipient lists for following types of e-mail:
1.766     raeburn  15244: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15245: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15246: module change checking, student/employee ID conflict checks, as
                   15247: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15248: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15249: 
                   15250: Inputs:
1.619     raeburn  15251: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15252: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15253: requestsmail, updatesmail, or idconflictsmail).
                   15254: 
1.619     raeburn  15255: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15256: 
1.619     raeburn  15257: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15258: i.e., predates configuration by DC via domainprefs.pm
                   15259: 
                   15260: $requname username of requester (if mailing type is helpdeskmail)
                   15261: 
                   15262: $requdom domain of requester (if mailing type is helpdeskmail)
                   15263: 
                   15264: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15265: 
1.618     raeburn  15266: 
1.655     raeburn  15267: Returns: comma separated list of addresses to which to send e-mail.
                   15268: 
                   15269: =back
1.618     raeburn  15270: 
                   15271: =cut
                   15272: 
                   15273: ############################################################
                   15274: ############################################################
                   15275: sub build_recipient_list {
1.1297    raeburn  15276:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15277:     my @recipients;
1.1270    raeburn  15278:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15279:     my %domconfig =
1.1270    raeburn  15280:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15281:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15282:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15283:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15284:                 my @contacts = ('adminemail','supportemail');
                   15285:                 foreach my $item (@contacts) {
                   15286:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15287:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15288:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15289:                             push(@recipients,$addr);
                   15290:                         }
1.619     raeburn  15291:                     }
1.1270    raeburn  15292:                 }
                   15293:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15294:                 if ($mailing eq 'helpdeskmail') {
                   15295:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15296:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15297:                         my @ok_bccs;
                   15298:                         foreach my $bcc (@bccs) {
                   15299:                             $bcc =~ s/^\s+//g;
                   15300:                             $bcc =~ s/\s+$//g;
                   15301:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15302:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15303:                                     push(@ok_bccs,$bcc);
                   15304:                                 }
                   15305:                             }
                   15306:                         }
                   15307:                         if (@ok_bccs > 0) {
                   15308:                             $allbcc = join(', ',@ok_bccs);
                   15309:                         }
                   15310:                     }
                   15311:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15312:                 }
                   15313:             }
1.766     raeburn  15314:         } elsif ($origmail ne '') {
1.1270    raeburn  15315:             $lastresort = $origmail;
1.618     raeburn  15316:         }
1.1297    raeburn  15317:         if ($mailing eq 'helpdeskmail') {
                   15318:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15319:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15320:                 my ($inststatus,$inststatus_checked);
                   15321:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15322:                     ($env{'user.domain'} ne 'public')) {
                   15323:                     $inststatus_checked = 1;
                   15324:                     $inststatus = $env{'environment.inststatus'};
                   15325:                 }
                   15326:                 unless ($inststatus_checked) {
                   15327:                     if (($requname ne '') && ($requdom ne '')) {
                   15328:                         if (($requname =~ /^$match_username$/) &&
                   15329:                             ($requdom =~ /^$match_domain$/) &&
                   15330:                             (&Apache::lonnet::domain($requdom))) {
                   15331:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15332:                                                                       $requdom);
                   15333:                             unless ($requhome eq 'no_host') {
                   15334:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15335:                                 $inststatus = $userenv{'inststatus'};
                   15336:                                 $inststatus_checked = 1;
                   15337:                             }
                   15338:                         }
                   15339:                     }
                   15340:                 }
                   15341:                 unless ($inststatus_checked) {
                   15342:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15343:                         my %srch = (srchby     => 'email',
                   15344:                                     srchdomain => $defdom,
                   15345:                                     srchterm   => $reqemail,
                   15346:                                     srchtype   => 'exact');
                   15347:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15348:                         foreach my $uname (keys(%srch_results)) {
                   15349:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15350:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15351:                                 $inststatus_checked = 1;
                   15352:                                 last;
                   15353:                             }
                   15354:                         }
                   15355:                         unless ($inststatus_checked) {
                   15356:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15357:                             if ($dirsrchres eq 'ok') {
                   15358:                                 foreach my $uname (keys(%srch_results)) {
                   15359:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15360:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15361:                                         $inststatus_checked = 1;
                   15362:                                         last;
                   15363:                                     }
                   15364:                                 }
                   15365:                             }
                   15366:                         }
                   15367:                     }
                   15368:                 }
                   15369:                 if ($inststatus ne '') {
                   15370:                     foreach my $status (split(/\:/,$inststatus)) {
                   15371:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15372:                             my @contacts = ('adminemail','supportemail');
                   15373:                             foreach my $item (@contacts) {
                   15374:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15375:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15376:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15377:                                         push(@recipients,$addr);
                   15378:                                     }
                   15379:                                 }
                   15380:                             }
                   15381:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15382:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15383:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15384:                                 my @ok_bccs;
                   15385:                                 foreach my $bcc (@bccs) {
                   15386:                                     $bcc =~ s/^\s+//g;
                   15387:                                     $bcc =~ s/\s+$//g;
                   15388:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15389:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15390:                                             push(@ok_bccs,$bcc);
                   15391:                                         }
                   15392:                                     }
                   15393:                                 }
                   15394:                                 if (@ok_bccs > 0) {
                   15395:                                     $allbcc = join(', ',@ok_bccs);
                   15396:                                 }
                   15397:                             }
                   15398:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15399:                             last;
                   15400:                         }
                   15401:                     }
                   15402:                 }
                   15403:             }
                   15404:         }
1.619     raeburn  15405:     } elsif ($origmail ne '') {
1.1270    raeburn  15406:         $lastresort = $origmail;
                   15407:     }
1.1297    raeburn  15408:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15409:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15410:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15411:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15412:             my %what = (
                   15413:                           perlvar => 1,
                   15414:                        );
                   15415:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15416:             if ($primary) {
                   15417:                 my $gotaddr;
                   15418:                 my ($result,$returnhash) =
                   15419:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15420:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15421:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15422:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15423:                         $gotaddr = 1;
                   15424:                     }
                   15425:                 }
                   15426:                 unless ($gotaddr) {
                   15427:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15428:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15429:                     unless ($uintdom eq $intdom) {
                   15430:                         my %domconfig =
                   15431:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15432:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15433:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15434:                                 my @contacts = ('adminemail','supportemail');
                   15435:                                 foreach my $item (@contacts) {
                   15436:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15437:                                         my $addr = $domconfig{'contacts'}{$item};
                   15438:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15439:                                             push(@recipients,$addr);
                   15440:                                         }
                   15441:                                     }
                   15442:                                 }
                   15443:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15444:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15445:                                 }
                   15446:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15447:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15448:                                     my @ok_bccs;
                   15449:                                     foreach my $bcc (@bccs) {
                   15450:                                         $bcc =~ s/^\s+//g;
                   15451:                                         $bcc =~ s/\s+$//g;
                   15452:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15453:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15454:                                                 push(@ok_bccs,$bcc);
                   15455:                                             }
                   15456:                                         }
                   15457:                                     }
                   15458:                                     if (@ok_bccs > 0) {
                   15459:                                         $allbcc = join(', ',@ok_bccs);
                   15460:                                     }
                   15461:                                 }
                   15462:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15463:                             }
                   15464:                         }
                   15465:                     }
                   15466:                 }
                   15467:             }
                   15468:         }
1.618     raeburn  15469:     }
1.688     raeburn  15470:     if (defined($defmail)) {
                   15471:         if ($defmail ne '') {
                   15472:             push(@recipients,$defmail);
                   15473:         }
1.618     raeburn  15474:     }
                   15475:     if ($otheremails) {
1.619     raeburn  15476:         my @others;
                   15477:         if ($otheremails =~ /,/) {
                   15478:             @others = split(/,/,$otheremails);
1.618     raeburn  15479:         } else {
1.619     raeburn  15480:             push(@others,$otheremails);
                   15481:         }
                   15482:         foreach my $addr (@others) {
                   15483:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15484:                 push(@recipients,$addr);
                   15485:             }
1.618     raeburn  15486:         }
                   15487:     }
1.1298    raeburn  15488:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15489:         if ((!@recipients) && ($lastresort ne '')) {
                   15490:             push(@recipients,$lastresort);
                   15491:         }
                   15492:     } elsif ($lastresort ne '') {
                   15493:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15494:             push(@recipients,$lastresort);
                   15495:         }
                   15496:     }
1.1271    raeburn  15497:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15498:     if (wantarray) {
                   15499:         return ($recipientlist,$allbcc,$addtext);
                   15500:     } else {
                   15501:         return $recipientlist;
                   15502:     }
1.618     raeburn  15503: }
                   15504: 
1.127     matthew  15505: ############################################################
                   15506: ############################################################
1.154     albertel 15507: 
1.655     raeburn  15508: =pod
                   15509: 
1.1224    musolffc 15510: =over 4
                   15511: 
1.1223    musolffc 15512: =item * &mime_email()
                   15513: 
                   15514: Sends an email with a possible attachment
                   15515: 
                   15516: Inputs:
                   15517: 
                   15518: =over 4
                   15519: 
                   15520: from -              Sender's email address
                   15521: 
1.1343    raeburn  15522: replyto -           Reply-To email address
                   15523: 
1.1223    musolffc 15524: to -                Email address of recipient
                   15525: 
                   15526: subject -           Subject of email
                   15527: 
                   15528: body -              Body of email
                   15529: 
                   15530: cc_string -         Carbon copy email address
                   15531: 
                   15532: bcc -               Blind carbon copy email address
                   15533: 
                   15534: attachment_path -   Path of file to be attached
                   15535: 
                   15536: file_name -         Name of file to be attached
                   15537: 
                   15538: attachment_text -   The body of an attachment of type "TEXT"
                   15539: 
                   15540: =back
                   15541: 
                   15542: =back
                   15543: 
                   15544: =cut
                   15545: 
                   15546: ############################################################
                   15547: ############################################################
                   15548: 
                   15549: sub mime_email {
1.1343    raeburn  15550:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15551:         $file_name,$attachment_text) = @_;
                   15552:  
1.1223    musolffc 15553:     my $msg = MIME::Lite->new(
                   15554:              From    => $from,
                   15555:              To      => $to,
                   15556:              Subject => $subject,
                   15557:              Type    =>'TEXT',
                   15558:              Data    => $body,
                   15559:              );
1.1343    raeburn  15560:     if ($replyto ne '') {
                   15561:         $msg->add("Reply-To" => $replyto);
                   15562:     }
1.1223    musolffc 15563:     if ($cc_string ne '') {
                   15564:         $msg->add("Cc" => $cc_string);
                   15565:     }
                   15566:     if ($bcc ne '') {
                   15567:         $msg->add("Bcc" => $bcc);
                   15568:     }
                   15569:     $msg->attr("content-type"         => "text/plain");
                   15570:     $msg->attr("content-type.charset" => "UTF-8");
                   15571:     # Attach file if given
                   15572:     if ($attachment_path) {
                   15573:         unless ($file_name) {
                   15574:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15575:         }
                   15576:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15577:         $msg->attach(Type     => $type,
                   15578:                      Path     => $attachment_path,
                   15579:                      Filename => $file_name
                   15580:                      );
                   15581:     # Otherwise attach text if given
                   15582:     } elsif ($attachment_text) {
                   15583:         $msg->attach(Type => 'TEXT',
                   15584:                      Data => $attachment_text);
                   15585:     }
                   15586:     # Send it
                   15587:     $msg->send('sendmail');
                   15588: }
                   15589: 
                   15590: ############################################################
                   15591: ############################################################
                   15592: 
                   15593: =pod
                   15594: 
1.655     raeburn  15595: =head1 Course Catalog Routines
                   15596: 
                   15597: =over 4
                   15598: 
                   15599: =item * &gather_categories()
                   15600: 
                   15601: Converts category definitions - keys of categories hash stored in  
                   15602: coursecategories in configuration.db on the primary library server in a 
                   15603: domain - to an array.  Also generates javascript and idx hash used to 
                   15604: generate Domain Coordinator interface for editing Course Categories.
                   15605: 
                   15606: Inputs:
1.663     raeburn  15607: 
1.655     raeburn  15608: categories (reference to hash of category definitions).
1.663     raeburn  15609: 
1.655     raeburn  15610: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15611:       categories and subcategories).
1.663     raeburn  15612: 
1.655     raeburn  15613: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15614:       editing Course Categories).
1.663     raeburn  15615: 
1.655     raeburn  15616: jsarray (reference to array of categories used to create Javascript arrays for
                   15617:          Domain Coordinator interface for editing Course Categories).
                   15618: 
                   15619: Returns: nothing
                   15620: 
                   15621: Side effects: populates cats, idx and jsarray. 
                   15622: 
                   15623: =cut
                   15624: 
                   15625: sub gather_categories {
                   15626:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15627:     my %counters;
                   15628:     my $num = 0;
                   15629:     foreach my $item (keys(%{$categories})) {
                   15630:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15631:         if ($container eq '' && $depth == 0) {
                   15632:             $cats->[$depth][$categories->{$item}] = $cat;
                   15633:         } else {
                   15634:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15635:         }
                   15636:         my ($escitem,$tail) = split(/:/,$item,2);
                   15637:         if ($counters{$tail} eq '') {
                   15638:             $counters{$tail} = $num;
                   15639:             $num ++;
                   15640:         }
                   15641:         if (ref($idx) eq 'HASH') {
                   15642:             $idx->{$item} = $counters{$tail};
                   15643:         }
                   15644:         if (ref($jsarray) eq 'ARRAY') {
                   15645:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15646:         }
                   15647:     }
                   15648:     return;
                   15649: }
                   15650: 
                   15651: =pod
                   15652: 
                   15653: =item * &extract_categories()
                   15654: 
                   15655: Used to generate breadcrumb trails for course categories.
                   15656: 
                   15657: Inputs:
1.663     raeburn  15658: 
1.655     raeburn  15659: categories (reference to hash of category definitions).
1.663     raeburn  15660: 
1.655     raeburn  15661: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15662:       categories and subcategories).
1.663     raeburn  15663: 
1.655     raeburn  15664: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15665: 
1.655     raeburn  15666: allitems (reference to hash - key is category key 
                   15667:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15668: 
1.655     raeburn  15669: idx (reference to hash of counters used in Domain Coordinator interface for
                   15670:       editing Course Categories).
1.663     raeburn  15671: 
1.655     raeburn  15672: jsarray (reference to array of categories used to create Javascript arrays for
                   15673:          Domain Coordinator interface for editing Course Categories).
                   15674: 
1.665     raeburn  15675: subcats (reference to hash of arrays containing all subcategories within each 
                   15676:          category, -recursive)
                   15677: 
1.1321    raeburn  15678: maxd (reference to hash used to hold max depth for all top-level categories).
                   15679: 
1.655     raeburn  15680: Returns: nothing
                   15681: 
                   15682: Side effects: populates trails and allitems hash references.
                   15683: 
                   15684: =cut
                   15685: 
                   15686: sub extract_categories {
1.1321    raeburn  15687:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15688:     if (ref($categories) eq 'HASH') {
                   15689:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15690:         if (ref($cats->[0]) eq 'ARRAY') {
                   15691:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15692:                 my $name = $cats->[0][$i];
                   15693:                 my $item = &escape($name).'::0';
                   15694:                 my $trailstr;
                   15695:                 if ($name eq 'instcode') {
                   15696:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15697:                 } elsif ($name eq 'communities') {
                   15698:                     $trailstr = &mt('Communities');
1.1239    raeburn  15699:                 } elsif ($name eq 'placement') {
                   15700:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15701:                 } else {
                   15702:                     $trailstr = $name;
                   15703:                 }
                   15704:                 if ($allitems->{$item} eq '') {
                   15705:                     push(@{$trails},$trailstr);
                   15706:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15707:                 }
                   15708:                 my @parents = ($name);
                   15709:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15710:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15711:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15712:                         if (ref($subcats) eq 'HASH') {
                   15713:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15714:                         }
1.1321    raeburn  15715:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15716:                     }
                   15717:                 } else {
                   15718:                     if (ref($subcats) eq 'HASH') {
                   15719:                         $subcats->{$item} = [];
1.655     raeburn  15720:                     }
1.1321    raeburn  15721:                     if (ref($maxd) eq 'HASH') {
                   15722:                         $maxd->{$name} = 1;
                   15723:                     }
1.655     raeburn  15724:                 }
                   15725:             }
                   15726:         }
                   15727:     }
                   15728:     return;
                   15729: }
                   15730: 
                   15731: =pod
                   15732: 
1.1162    raeburn  15733: =item * &recurse_categories()
1.655     raeburn  15734: 
                   15735: Recursively used to generate breadcrumb trails for course categories.
                   15736: 
                   15737: Inputs:
1.663     raeburn  15738: 
1.655     raeburn  15739: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15740:       categories and subcategories).
1.663     raeburn  15741: 
1.655     raeburn  15742: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15743: 
                   15744: category (current course category, for which breadcrumb trail is being generated).
                   15745: 
                   15746: trails (reference to array of breadcrumb trails for each category).
                   15747: 
1.655     raeburn  15748: allitems (reference to hash - key is category key
                   15749:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15750: 
1.655     raeburn  15751: parents (array containing containers directories for current category, 
                   15752:          back to top level). 
                   15753: 
                   15754: Returns: nothing
                   15755: 
                   15756: Side effects: populates trails and allitems hash references
                   15757: 
                   15758: =cut
                   15759: 
                   15760: sub recurse_categories {
1.1321    raeburn  15761:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15762:     my $shallower = $depth - 1;
                   15763:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15764:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15765:             my $name = $cats->[$depth]{$category}[$k];
                   15766:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15767:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15768:             if ($allitems->{$item} eq '') {
                   15769:                 push(@{$trails},$trailstr);
                   15770:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15771:             }
                   15772:             my $deeper = $depth+1;
                   15773:             push(@{$parents},$category);
1.665     raeburn  15774:             if (ref($subcats) eq 'HASH') {
                   15775:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15776:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15777:                     my $higher;
                   15778:                     if ($j > 0) {
                   15779:                         $higher = &escape($parents->[$j]).':'.
                   15780:                                   &escape($parents->[$j-1]).':'.$j;
                   15781:                     } else {
                   15782:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15783:                     }
                   15784:                     push(@{$subcats->{$higher}},$subcat);
                   15785:                 }
                   15786:             }
                   15787:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  15788:                                 $subcats,$maxd);
1.655     raeburn  15789:             pop(@{$parents});
                   15790:         }
                   15791:     } else {
                   15792:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15793:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15794:         if ($allitems->{$item} eq '') {
                   15795:             push(@{$trails},$trailstr);
                   15796:             $allitems->{$item} = scalar(@{$trails})-1;
                   15797:         }
1.1321    raeburn  15798:         if (ref($maxd) eq 'HASH') {
                   15799:             if ($depth > $maxd->{$parents->[0]}) {
                   15800:                 $maxd->{$parents->[0]} = $depth;
                   15801:             }
                   15802:         }
1.655     raeburn  15803:     }
                   15804:     return;
                   15805: }
                   15806: 
1.663     raeburn  15807: =pod
                   15808: 
1.1162    raeburn  15809: =item * &assign_categories_table()
1.663     raeburn  15810: 
                   15811: Create a datatable for display of hierarchical categories in a domain,
                   15812: with checkboxes to allow a course to be categorized. 
                   15813: 
                   15814: Inputs:
                   15815: 
                   15816: cathash - reference to hash of categories defined for the domain (from
                   15817:           configuration.db)
                   15818: 
                   15819: currcat - scalar with an & separated list of categories assigned to a course. 
                   15820: 
1.919     raeburn  15821: type    - scalar contains course type (Course or Community).
                   15822: 
1.1260    raeburn  15823: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15824:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15825: 
1.663     raeburn  15826: Returns: $output (markup to be displayed) 
                   15827: 
                   15828: =cut
                   15829: 
                   15830: sub assign_categories_table {
1.1259    raeburn  15831:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15832:     my $output;
                   15833:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  15834:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15835:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15836:         $maxdepth = scalar(@cats);
                   15837:         if (@cats > 0) {
                   15838:             my $itemcount = 0;
                   15839:             if (ref($cats[0]) eq 'ARRAY') {
                   15840:                 my @currcategories;
                   15841:                 if ($currcat ne '') {
                   15842:                     @currcategories = split('&',$currcat);
                   15843:                 }
1.919     raeburn  15844:                 my $table;
1.663     raeburn  15845:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15846:                     my $parent = $cats[0][$i];
1.919     raeburn  15847:                     next if ($parent eq 'instcode');
                   15848:                     if ($type eq 'Community') {
                   15849:                         next unless ($parent eq 'communities');
1.1239    raeburn  15850:                     } elsif ($type eq 'Placement') {
                   15851:                         next unless ($parent eq 'placement');
1.919     raeburn  15852:                     } else {
1.1239    raeburn  15853:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15854:                     }
1.663     raeburn  15855:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15856:                     my $item = &escape($parent).'::0';
                   15857:                     my $checked = '';
                   15858:                     if (@currcategories > 0) {
                   15859:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15860:                             $checked = ' checked="checked"';
1.663     raeburn  15861:                         }
                   15862:                     }
1.919     raeburn  15863:                     my $parent_title = $parent;
                   15864:                     if ($parent eq 'communities') {
                   15865:                         $parent_title = &mt('Communities');
1.1239    raeburn  15866:                     } elsif ($parent eq 'placement') {
                   15867:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15868:                     }
                   15869:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15870:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15871:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15872:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15873:                     my $depth = 1;
                   15874:                     push(@path,$parent);
1.1259    raeburn  15875:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15876:                     pop(@path);
1.919     raeburn  15877:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15878:                     $itemcount ++;
                   15879:                 }
1.919     raeburn  15880:                 if ($itemcount) {
                   15881:                     $output = &Apache::loncommon::start_data_table().
                   15882:                               $table.
                   15883:                               &Apache::loncommon::end_data_table();
                   15884:                 }
1.663     raeburn  15885:             }
                   15886:         }
                   15887:     }
                   15888:     return $output;
                   15889: }
                   15890: 
                   15891: =pod
                   15892: 
1.1162    raeburn  15893: =item * &assign_category_rows()
1.663     raeburn  15894: 
                   15895: Create a datatable row for display of nested categories in a domain,
                   15896: with checkboxes to allow a course to be categorized,called recursively.
                   15897: 
                   15898: Inputs:
                   15899: 
                   15900: itemcount - track row number for alternating colors
                   15901: 
                   15902: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15903:       categories and subcategories.
                   15904: 
                   15905: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15906: 
                   15907: parent - parent of current category item
                   15908: 
                   15909: path - Array containing all categories back up through the hierarchy from the
                   15910:        current category to the top level.
                   15911: 
                   15912: currcategories - reference to array of current categories assigned to the course
                   15913: 
1.1260    raeburn  15914: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15915:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15916: 
1.663     raeburn  15917: Returns: $output (markup to be displayed).
                   15918: 
                   15919: =cut
                   15920: 
                   15921: sub assign_category_rows {
1.1259    raeburn  15922:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15923:     my ($text,$name,$item,$chgstr);
                   15924:     if (ref($cats) eq 'ARRAY') {
                   15925:         my $maxdepth = scalar(@{$cats});
                   15926:         if (ref($cats->[$depth]) eq 'HASH') {
                   15927:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15928:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15929:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15930:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15931:                 for (my $j=0; $j<$numchildren; $j++) {
                   15932:                     $name = $cats->[$depth]{$parent}[$j];
                   15933:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15934:                     my $deeper = $depth+1;
                   15935:                     my $checked = '';
                   15936:                     if (ref($currcategories) eq 'ARRAY') {
                   15937:                         if (@{$currcategories} > 0) {
                   15938:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15939:                                 $checked = ' checked="checked"';
1.663     raeburn  15940:                             }
                   15941:                         }
                   15942:                     }
1.664     raeburn  15943:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15944:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15945:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15946:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15947:                              '</td><td>';
1.663     raeburn  15948:                     if (ref($path) eq 'ARRAY') {
                   15949:                         push(@{$path},$name);
1.1259    raeburn  15950:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15951:                         pop(@{$path});
                   15952:                     }
                   15953:                     $text .= '</td></tr>';
                   15954:                 }
                   15955:                 $text .= '</table></td>';
                   15956:             }
                   15957:         }
                   15958:     }
                   15959:     return $text;
                   15960: }
                   15961: 
1.1181    raeburn  15962: =pod
                   15963: 
                   15964: =back
                   15965: 
                   15966: =cut
                   15967: 
1.655     raeburn  15968: ############################################################
                   15969: ############################################################
                   15970: 
                   15971: 
1.443     albertel 15972: sub commit_customrole {
1.664     raeburn  15973:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15974:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15975:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15976:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15977:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15978:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15979:                  '</b><br />';
                   15980:     return $output;
                   15981: }
                   15982: 
                   15983: sub commit_standardrole {
1.1116    raeburn  15984:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15985:     my ($output,$logmsg,$linefeed);
                   15986:     if ($context eq 'auto') {
                   15987:         $linefeed = "\n";
                   15988:     } else {
                   15989:         $linefeed = "<br />\n";
                   15990:     }  
1.443     albertel 15991:     if ($three eq 'st') {
1.541     raeburn  15992:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15993:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15994:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15995:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15996:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15997:         } else {
1.541     raeburn  15998:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15999:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16000:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16001:             if ($context eq 'auto') {
                   16002:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16003:             } else {
                   16004:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16005:                &mt('Add to classlist').': <b>ok</b>';
                   16006:             }
                   16007:             $output .= $linefeed;
1.443     albertel 16008:         }
                   16009:     } else {
                   16010:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16011:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16012:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16013:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16014:         if ($context eq 'auto') {
                   16015:             $output .= $result.$linefeed;
                   16016:         } else {
                   16017:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16018:         }
1.443     albertel 16019:     }
                   16020:     return $output;
                   16021: }
                   16022: 
                   16023: sub commit_studentrole {
1.1116    raeburn  16024:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16025:         $credits) = @_;
1.626     raeburn  16026:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16027:     if ($context eq 'auto') {
                   16028:         $linefeed = "\n";
                   16029:     } else {
                   16030:         $linefeed = '<br />'."\n";
                   16031:     }
1.443     albertel 16032:     if (defined($one) && defined($two)) {
                   16033:         my $cid=$one.'_'.$two;
                   16034:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16035:         my $secchange = 0;
                   16036:         my $expire_role_result;
                   16037:         my $modify_section_result;
1.628     raeburn  16038:         if ($oldsec ne '-1') { 
                   16039:             if ($oldsec ne $sec) {
1.443     albertel 16040:                 $secchange = 1;
1.628     raeburn  16041:                 my $now = time;
1.443     albertel 16042:                 my $uurl='/'.$cid;
                   16043:                 $uurl=~s/\_/\//g;
                   16044:                 if ($oldsec) {
                   16045:                     $uurl.='/'.$oldsec;
                   16046:                 }
1.626     raeburn  16047:                 $oldsecurl = $uurl;
1.628     raeburn  16048:                 $expire_role_result = 
1.652     raeburn  16049:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16050:                 if ($env{'request.course.sec'} ne '') { 
                   16051:                     if ($expire_role_result eq 'refused') {
                   16052:                         my @roles = ('st');
                   16053:                         my @statuses = ('previous');
                   16054:                         my @roledoms = ($one);
                   16055:                         my $withsec = 1;
                   16056:                         my %roleshash = 
                   16057:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16058:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16059:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16060:                             my ($oldstart,$oldend) = 
                   16061:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16062:                             if ($oldend > 0 && $oldend <= $now) {
                   16063:                                 $expire_role_result = 'ok';
                   16064:                             }
                   16065:                         }
                   16066:                     }
                   16067:                 }
1.443     albertel 16068:                 $result = $expire_role_result;
                   16069:             }
                   16070:         }
                   16071:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16072:             $modify_section_result = 
                   16073:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16074:                                                            undef,undef,undef,$sec,
                   16075:                                                            $end,$start,'','',$cid,
                   16076:                                                            '',$context,$credits);
1.443     albertel 16077:             if ($modify_section_result =~ /^ok/) {
                   16078:                 if ($secchange == 1) {
1.628     raeburn  16079:                     if ($sec eq '') {
                   16080:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16081:                     } else {
                   16082:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16083:                     }
1.443     albertel 16084:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16085:                     if ($sec eq '') {
                   16086:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16087:                     } else {
                   16088:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16089:                     }
1.443     albertel 16090:                 } else {
1.628     raeburn  16091:                     if ($sec eq '') {
                   16092:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16093:                     } else {
                   16094:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16095:                     }
1.443     albertel 16096:                 }
                   16097:             } else {
1.1115    raeburn  16098:                 if ($secchange) { 
1.628     raeburn  16099:                     $$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;
                   16100:                 } else {
                   16101:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16102:                 }
1.443     albertel 16103:             }
                   16104:             $result = $modify_section_result;
                   16105:         } elsif ($secchange == 1) {
1.628     raeburn  16106:             if ($oldsec eq '') {
1.1103    raeburn  16107:                 $$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  16108:             } else {
                   16109:                 $$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;
                   16110:             }
1.626     raeburn  16111:             if ($expire_role_result eq 'refused') {
                   16112:                 my $newsecurl = '/'.$cid;
                   16113:                 $newsecurl =~ s/\_/\//g;
                   16114:                 if ($sec ne '') {
                   16115:                     $newsecurl.='/'.$sec;
                   16116:                 }
                   16117:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16118:                     if ($sec eq '') {
                   16119:                         $$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;
                   16120:                     } else {
                   16121:                         $$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;
                   16122:                     }
                   16123:                 }
                   16124:             }
1.443     albertel 16125:         }
                   16126:     } else {
1.626     raeburn  16127:         $$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 16128:         $result = "error: incomplete course id\n";
                   16129:     }
                   16130:     return $result;
                   16131: }
                   16132: 
1.1108    raeburn  16133: sub show_role_extent {
                   16134:     my ($scope,$context,$role) = @_;
                   16135:     $scope =~ s{^/}{};
                   16136:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16137:     push(@courseroles,'co');
                   16138:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16139:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16140:         $scope =~ s{/}{_};
                   16141:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16142:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16143:         my ($audom,$auname) = split(/\//,$scope);
                   16144:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16145:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16146:     } else {
                   16147:         $scope =~ s{/$}{};
                   16148:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16149:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16150:     }
                   16151: }
                   16152: 
1.443     albertel 16153: ############################################################
                   16154: ############################################################
                   16155: 
1.566     albertel 16156: sub check_clone {
1.578     raeburn  16157:     my ($args,$linefeed) = @_;
1.566     albertel 16158:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16159:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16160:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16161:     my $clonetitle;
                   16162:     my @clonemsg;
1.566     albertel 16163:     my $can_clone = 0;
1.944     raeburn  16164:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16165:     if ($lctype ne 'community') {
                   16166:         $lctype = 'course';
                   16167:     }
1.566     albertel 16168:     if ($clonehome eq 'no_host') {
1.944     raeburn  16169:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16170:             push(@clonemsg,({
                   16171:                               mt => 'No new community created.',
                   16172:                               args => [],
                   16173:                             },
                   16174:                             {
                   16175:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16176:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16177:                             }));
1.908     raeburn  16178:         } else {
1.1344    raeburn  16179:             push(@clonemsg,({
                   16180:                               mt => 'No new course created.',
                   16181:                               args => [],
                   16182:                             },
                   16183:                             {
                   16184:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16185:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16186:                             }));
                   16187:         }
1.566     albertel 16188:     } else {
                   16189: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16190:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16191:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16192:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16193:                 push(@clonemsg,({
                   16194:                                   mt => 'No new community created.',
                   16195:                                   args => [],
                   16196:                                 },
                   16197:                                 {
                   16198:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16199:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16200:                                 }));
                   16201:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16202:             }
                   16203:         }
1.1262    raeburn  16204: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16205:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16206: 	    $can_clone = 1;
                   16207: 	} else {
1.1221    raeburn  16208: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16209: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16210:             if ($clonehash{'cloners'} eq '') {
                   16211:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16212:                 if ($domdefs{'canclone'}) {
                   16213:                     unless ($domdefs{'canclone'} eq 'none') {
                   16214:                         if ($domdefs{'canclone'} eq 'domain') {
                   16215:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16216:                                 $can_clone = 1;
                   16217:                             }
                   16218:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16219:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16220:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16221:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16222:                                 $can_clone = 1;
                   16223:                             }
                   16224:                         }
                   16225:                     }
                   16226:                 }
1.578     raeburn  16227:             } else {
1.1221    raeburn  16228: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16229:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16230:                     $can_clone = 1;
1.1221    raeburn  16231:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16232:                     $can_clone = 1;
1.1225    raeburn  16233:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16234:                     $can_clone = 1;
1.1221    raeburn  16235:                 }
                   16236:                 unless ($can_clone) {
1.1225    raeburn  16237:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16238:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16239:                         my (%gotdomdefaults,%gotcodedefaults);
                   16240:                         foreach my $cloner (@cloners) {
                   16241:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16242:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16243:                                 my (%codedefaults,@code_order);
                   16244:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16245:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16246:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16247:                                     }
                   16248:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16249:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16250:                                     }
                   16251:                                 } else {
                   16252:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16253:                                                                             \%codedefaults,
                   16254:                                                                             \@code_order);
                   16255:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16256:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16257:                                 }
                   16258:                                 if (@code_order > 0) {
                   16259:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16260:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16261:                                                                                 $args->{'crscode'})) {
                   16262:                                         $can_clone = 1;
                   16263:                                         last;
                   16264:                                     }
                   16265:                                 }
                   16266:                             }
                   16267:                         }
                   16268:                     }
1.1225    raeburn  16269:                 }
                   16270:             }
                   16271:             unless ($can_clone) {
                   16272:                 my $ccrole = 'cc';
                   16273:                 if ($args->{'crstype'} eq 'Community') {
                   16274:                     $ccrole = 'co';
                   16275:                 }
                   16276: 	        my %roleshash =
                   16277: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16278: 					          $args->{'ccdomain'},
                   16279:                                                   'userroles',['active'],[$ccrole],
                   16280: 					          [$args->{'clonedomain'}]);
                   16281: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16282:                     $can_clone = 1;
                   16283:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16284:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16285:                     $can_clone = 1;
1.1221    raeburn  16286:                 }
                   16287:             }
                   16288:             unless ($can_clone) {
                   16289:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16290:                     push(@clonemsg,({
                   16291:                                       mt => 'No new community created.',
                   16292:                                       args => [],
                   16293:                                     },
                   16294:                                     {
                   16295:                                       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]).',
                   16296:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16297:                                     }));
1.942     raeburn  16298:                 } else {
1.1344    raeburn  16299:                     push(@clonemsg,({
                   16300:                                       mt => 'No new course created.',
                   16301:                                       args => [],
                   16302:                                     },
                   16303:                                     {
                   16304:                                       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]).',
                   16305:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16306:                                     }));
1.1221    raeburn  16307:                 }
1.566     albertel 16308: 	    }
1.578     raeburn  16309:         }
1.566     albertel 16310:     }
1.1344    raeburn  16311:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16312: }
                   16313: 
1.444     albertel 16314: sub construct_course {
1.1262    raeburn  16315:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16316:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16317:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16318:     my $linefeed =  '<br />'."\n";
                   16319:     if ($context eq 'auto') {
                   16320:         $linefeed = "\n";
                   16321:     }
1.566     albertel 16322: 
                   16323: #
                   16324: # Are we cloning?
                   16325: #
1.1344    raeburn  16326:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16327:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16328: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16329:         if (!$can_clone) {
1.1344    raeburn  16330: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16331: 	}
                   16332:     }
                   16333: 
1.444     albertel 16334: #
                   16335: # Open course
                   16336: #
1.1239    raeburn  16337:     my $showncrstype;
                   16338:     if ($args->{'crstype'} eq 'Placement') {
                   16339:         $showncrstype = 'placement test'; 
                   16340:     } else {  
                   16341:         $showncrstype = lc($args->{'crstype'});
                   16342:     }
1.444     albertel 16343:     my %cenv=();
                   16344:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16345:                                              $args->{'cdescr'},
                   16346:                                              $args->{'curl'},
                   16347:                                              $args->{'course_home'},
                   16348:                                              $args->{'nonstandard'},
                   16349:                                              $args->{'crscode'},
                   16350:                                              $args->{'ccuname'}.':'.
                   16351:                                              $args->{'ccdomain'},
1.882     raeburn  16352:                                              $args->{'crstype'},
1.1344    raeburn  16353:                                              $cnum,$context,$category,
                   16354:                                              $callercontext);
1.444     albertel 16355: 
                   16356:     # Note: The testing routines depend on this being output; see 
                   16357:     # Utils::Course. This needs to at least be output as a comment
                   16358:     # if anyone ever decides to not show this, and Utils::Course::new
                   16359:     # will need to be suitably modified.
1.1344    raeburn  16360:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16361:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16362:     } else {
                   16363:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16364:     }
1.943     raeburn  16365:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16366:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16367:     }
                   16368: 
1.444     albertel 16369: #
                   16370: # Check if created correctly
                   16371: #
1.479     albertel 16372:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16373:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16374:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16375:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16376:             $outcome .= &mt_user($user_lh,
                   16377:                             'Course creation failed, unrecognized course home server.');
                   16378:         } else {
                   16379:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16380:         }
                   16381:         $outcome .= $linefeed;
                   16382:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16383:     }
1.541     raeburn  16384:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16385: 
1.444     albertel 16386: #
1.566     albertel 16387: # Do the cloning
                   16388: #   
1.1344    raeburn  16389:     my @clonemsg;
1.566     albertel 16390:     if ($can_clone && $cloneid) {
1.1344    raeburn  16391:         push(@clonemsg,
                   16392:                       {
                   16393:                           mt => 'Created [_1] by cloning from [_2]',
                   16394:                           args => [$showncrstype,$clonetitle],
                   16395:                       });
1.566     albertel 16396: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16397: # Copy all files
1.1344    raeburn  16398:         my @info =
                   16399: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16400: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16401:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16402:                                                      $args->{'tinyurls'});
                   16403:         if (@info) {
                   16404:             push(@clonemsg,@info);
                   16405:         }
1.444     albertel 16406: # Restore URL
1.566     albertel 16407: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16408: # Restore title
1.566     albertel 16409: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16410: # Restore creation date, creator and creation context.
                   16411:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16412:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16413:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16414: # Mark as cloned
1.566     albertel 16415: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16416: # Need to clone grading mode
                   16417:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16418:         $cenv{'grading'}=$newenv{'grading'};
                   16419: # Do not clone these environment entries
                   16420:         &Apache::lonnet::del('environment',
                   16421:                   ['default_enrollment_start_date',
                   16422:                    'default_enrollment_end_date',
                   16423:                    'question.email',
                   16424:                    'policy.email',
                   16425:                    'comment.email',
                   16426:                    'pch.users.denied',
1.725     raeburn  16427:                    'plc.users.denied',
                   16428:                    'hidefromcat',
1.1121    raeburn  16429:                    'checkforpriv',
1.1355    raeburn  16430:                    'categories'],
1.638     www      16431:                    $$crsudom,$$crsunum);
1.1170    raeburn  16432:         if ($args->{'textbook'}) {
                   16433:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16434:         }
1.444     albertel 16435:     }
1.566     albertel 16436: 
1.444     albertel 16437: #
                   16438: # Set environment (will override cloned, if existing)
                   16439: #
                   16440:     my @sections = ();
                   16441:     my @xlists = ();
                   16442:     if ($args->{'crstype'}) {
                   16443:         $cenv{'type'}=$args->{'crstype'};
                   16444:     }
                   16445:     if ($args->{'crsid'}) {
                   16446:         $cenv{'courseid'}=$args->{'crsid'};
                   16447:     }
                   16448:     if ($args->{'crscode'}) {
                   16449:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16450:     }
                   16451:     if ($args->{'crsquota'} ne '') {
                   16452:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16453:     } else {
                   16454:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16455:     }
                   16456:     if ($args->{'ccuname'}) {
                   16457:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16458:                                         ':'.$args->{'ccdomain'};
                   16459:     } else {
                   16460:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16461:     }
1.1116    raeburn  16462:     if ($args->{'defaultcredits'}) {
                   16463:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16464:     }
1.444     albertel 16465:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16466:     if ($args->{'crssections'}) {
                   16467:         $cenv{'internal.sectionnums'} = '';
                   16468:         if ($args->{'crssections'} =~ m/,/) {
                   16469:             @sections = split/,/,$args->{'crssections'};
                   16470:         } else {
                   16471:             $sections[0] = $args->{'crssections'};
                   16472:         }
                   16473:         if (@sections > 0) {
                   16474:             foreach my $item (@sections) {
                   16475:                 my ($sec,$gp) = split/:/,$item;
                   16476:                 my $class = $args->{'crscode'}.$sec;
                   16477:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16478:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16479:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16480:                     push(@badclasses,$class);
1.444     albertel 16481:                 }
                   16482:             }
                   16483:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16484:         }
                   16485:     }
                   16486: # do not hide course coordinator from staff listing, 
                   16487: # even if privileged
                   16488:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16489: # add course coordinator's domain to domains to check for privileged users
                   16490: # if different to course domain
                   16491:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16492:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16493:     }
1.444     albertel 16494: # add crosslistings
                   16495:     if ($args->{'crsxlist'}) {
                   16496:         $cenv{'internal.crosslistings'}='';
                   16497:         if ($args->{'crsxlist'} =~ m/,/) {
                   16498:             @xlists = split/,/,$args->{'crsxlist'};
                   16499:         } else {
                   16500:             $xlists[0] = $args->{'crsxlist'};
                   16501:         }
                   16502:         if (@xlists > 0) {
                   16503:             foreach my $item (@xlists) {
                   16504:                 my ($xl,$gp) = split/:/,$item;
                   16505:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16506:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16507:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16508:                     push(@badclasses,$xl);
1.444     albertel 16509:                 }
                   16510:             }
                   16511:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16512:         }
                   16513:     }
                   16514:     if ($args->{'autoadds'}) {
                   16515:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16516:     }
                   16517:     if ($args->{'autodrops'}) {
                   16518:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16519:     }
                   16520: # check for notification of enrollment changes
                   16521:     my @notified = ();
                   16522:     if ($args->{'notify_owner'}) {
                   16523:         if ($args->{'ccuname'} ne '') {
                   16524:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16525:         }
                   16526:     }
                   16527:     if ($args->{'notify_dc'}) {
                   16528:         if ($uname ne '') { 
1.630     raeburn  16529:             push(@notified,$uname.':'.$udom);
1.444     albertel 16530:         }
                   16531:     }
                   16532:     if (@notified > 0) {
                   16533:         my $notifylist;
                   16534:         if (@notified > 1) {
                   16535:             $notifylist = join(',',@notified);
                   16536:         } else {
                   16537:             $notifylist = $notified[0];
                   16538:         }
                   16539:         $cenv{'internal.notifylist'} = $notifylist;
                   16540:     }
                   16541:     if (@badclasses > 0) {
                   16542:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16543:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16544:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16545:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16546:         );
1.1264    raeburn  16547:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16548:                            &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  16549:         if ($context eq 'auto') {
                   16550:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16551:         } else {
1.566     albertel 16552:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16553:         }
                   16554:         foreach my $item (@badclasses) {
1.541     raeburn  16555:             if ($context eq 'auto') {
1.1261    raeburn  16556:                 $outcome .= " - $item\n";
1.541     raeburn  16557:             } else {
1.1261    raeburn  16558:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16559:             }
1.1261    raeburn  16560:         }
                   16561:         if ($context eq 'auto') {
                   16562:             $outcome .= $linefeed;
                   16563:         } else {
                   16564:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16565:         } 
1.444     albertel 16566:     }
                   16567:     if ($args->{'no_end_date'}) {
                   16568:         $args->{'endaccess'} = 0;
                   16569:     }
                   16570:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16571:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16572:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16573:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16574:     if ($args->{'showphotos'}) {
                   16575:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16576:     }
                   16577:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16578:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16579:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16580:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16581:             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'); 
                   16582:             if ($context eq 'auto') {
                   16583:                 $outcome .= $krb_msg;
                   16584:             } else {
1.566     albertel 16585:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16586:             }
                   16587:             $outcome .= $linefeed;
1.444     albertel 16588:         }
                   16589:     }
                   16590:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16591:        if ($args->{'setpolicy'}) {
                   16592:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16593:        }
                   16594:        if ($args->{'setcontent'}) {
                   16595:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16596:        }
1.1251    raeburn  16597:        if ($args->{'setcomment'}) {
                   16598:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16599:        }
1.444     albertel 16600:     }
                   16601:     if ($args->{'reshome'}) {
                   16602: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16603: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16604:     }
                   16605: #
                   16606: # course has keyed access
                   16607: #
                   16608:     if ($args->{'setkeys'}) {
                   16609:        $cenv{'keyaccess'}='yes';
                   16610:     }
                   16611: # if specified, key authority is not course, but user
                   16612: # only active if keyaccess is yes
                   16613:     if ($args->{'keyauth'}) {
1.487     albertel 16614: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16615: 	$user = &LONCAPA::clean_username($user);
                   16616: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16617: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16618: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16619: 	}
                   16620:     }
                   16621: 
1.1166    raeburn  16622: #
1.1167    raeburn  16623: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16624: #
                   16625:     if ($args->{'uniquecode'}) {
                   16626:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16627:         if ($code) {
                   16628:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16629:             my %crsinfo =
                   16630:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16631:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16632:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16633:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16634:             } 
1.1166    raeburn  16635:             if (ref($coderef)) {
                   16636:                 $$coderef = $code;
                   16637:             }
                   16638:         }
                   16639:     }
                   16640: 
1.444     albertel 16641:     if ($args->{'disresdis'}) {
                   16642:         $cenv{'pch.roles.denied'}='st';
                   16643:     }
                   16644:     if ($args->{'disablechat'}) {
                   16645:         $cenv{'plc.roles.denied'}='st';
                   16646:     }
                   16647: 
                   16648:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16649:     # course
                   16650:     $cenv{'course.helper.not.run'} = 1;
                   16651:     #
                   16652:     # Use new Randomseed
                   16653:     #
                   16654:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16655:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16656:     #
                   16657:     # The encryption code and receipt prefix for this course
                   16658:     #
                   16659:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16660:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16661:     #
                   16662:     # By default, use standard grading
                   16663:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16664: 
1.541     raeburn  16665:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16666:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16667: #
                   16668: # Open all assignments
                   16669: #
                   16670:     if ($args->{'openall'}) {
1.1341    raeburn  16671:        my $opendate = time;
                   16672:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16673:            $opendate = $args->{'openallfrom'};
                   16674:        }
1.444     albertel 16675:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16676:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16677:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16678:        $outcome .= &mt('All assignments open starting [_1]',
                   16679:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16680:                    &Apache::lonnet::cput
                   16681:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16682:    }
                   16683: #
                   16684: # Set first page
                   16685: #
                   16686:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16687: 	    || ($cloneid)) {
1.445     albertel 16688: 	use LONCAPA::map;
1.444     albertel 16689: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16690: 
                   16691: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16692:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16693: 
1.444     albertel 16694:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16695:         my $title; my $url;
                   16696:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16697: 	    $title=&mt('Syllabus');
1.444     albertel 16698:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16699:         } else {
1.963     raeburn  16700:             $title=&mt('Table of Contents');
1.444     albertel 16701:             $url='/adm/navmaps';
                   16702:         }
1.445     albertel 16703: 
                   16704:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16705: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16706: 
                   16707: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16708:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16709:     }
1.566     albertel 16710: 
1.1237    raeburn  16711: # 
                   16712: # Set params for Placement Tests
                   16713: #
1.1239    raeburn  16714:     if ($args->{'crstype'} eq 'Placement') {
                   16715:        my %storecontent; 
                   16716:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16717:        my %defaults = (
                   16718:                         buttonshide   => { value => 'yes',
                   16719:                                            type => 'string_yesno',},
                   16720:                         type          => { value => 'randomizetry',
                   16721:                                            type  => 'string_questiontype',},
                   16722:                         maxtries      => { value => 1,
                   16723:                                            type => 'int_pos',},
                   16724:                         problemstatus => { value => 'no',
                   16725:                                            type  => 'string_problemstatus',},
                   16726:                       );
                   16727:        foreach my $key (keys(%defaults)) {
                   16728:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16729:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16730:        }
1.1237    raeburn  16731:        &Apache::lonnet::cput
                   16732:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16733:     }
                   16734: 
1.1344    raeburn  16735:     return (1,$outcome,\@clonemsg);
1.444     albertel 16736: }
                   16737: 
1.1166    raeburn  16738: sub make_unique_code {
                   16739:     my ($cdom,$cnum) = @_;
                   16740:     # get lock on uniquecodes db
                   16741:     my $lockhash = {
                   16742:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16743:                                                   ':'.$env{'user.domain'},
                   16744:                    };
                   16745:     my $tries = 0;
                   16746:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16747:     my ($code,$error);
                   16748:   
                   16749:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16750:         $tries ++;
                   16751:         sleep 1;
                   16752:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16753:     }
                   16754:     if ($gotlock eq 'ok') {
                   16755:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16756:         my $gotcode;
                   16757:         my $attempts = 0;
                   16758:         while ((!$gotcode) && ($attempts < 100)) {
                   16759:             $code = &generate_code();
                   16760:             if (!exists($currcodes{$code})) {
                   16761:                 $gotcode = 1;
                   16762:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16763:                     $error = 'nostore';
                   16764:                 }
                   16765:             }
                   16766:             $attempts ++;
                   16767:         }
                   16768:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16769:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16770:     } else {
                   16771:         $error = 'nolock';
                   16772:     }
                   16773:     return ($code,$error);
                   16774: }
                   16775: 
                   16776: sub generate_code {
                   16777:     my $code;
                   16778:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16779:     for (my $i=0; $i<6; $i++) {
                   16780:         my $lettnum = int (rand 2);
                   16781:         my $item = '';
                   16782:         if ($lettnum) {
                   16783:             $item = $letts[int( rand(18) )];
                   16784:         } else {
                   16785:             $item = 1+int( rand(8) );
                   16786:         }
                   16787:         $code .= $item;
                   16788:     }
                   16789:     return $code;
                   16790: }
                   16791: 
1.444     albertel 16792: ############################################################
                   16793: ############################################################
                   16794: 
1.1237    raeburn  16795: # Community, Course and Placement Test
1.378     raeburn  16796: sub course_type {
                   16797:     my ($cid) = @_;
                   16798:     if (!defined($cid)) {
                   16799:         $cid = $env{'request.course.id'};
                   16800:     }
1.404     albertel 16801:     if (defined($env{'course.'.$cid.'.type'})) {
                   16802:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16803:     } else {
                   16804:         return 'Course';
1.377     raeburn  16805:     }
                   16806: }
1.156     albertel 16807: 
1.406     raeburn  16808: sub group_term {
                   16809:     my $crstype = &course_type();
                   16810:     my %names = (
                   16811:                   'Course' => 'group',
1.865     raeburn  16812:                   'Community' => 'group',
1.1237    raeburn  16813:                   'Placement' => 'group',
1.406     raeburn  16814:                 );
                   16815:     return $names{$crstype};
                   16816: }
                   16817: 
1.902     raeburn  16818: sub course_types {
1.1310    raeburn  16819:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16820:     my %typename = (
                   16821:                          official   => 'Official course',
                   16822:                          unofficial => 'Unofficial course',
                   16823:                          community  => 'Community',
1.1165    raeburn  16824:                          textbook   => 'Textbook course',
1.1237    raeburn  16825:                          placement  => 'Placement test',
1.1310    raeburn  16826:                          lti        => 'LTI provider',
1.902     raeburn  16827:                    );
                   16828:     return (\@types,\%typename);
                   16829: }
                   16830: 
1.156     albertel 16831: sub icon {
                   16832:     my ($file)=@_;
1.505     albertel 16833:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16834:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16835:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16836:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16837: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16838: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16839: 	            $curfext.".gif") {
                   16840: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16841: 		$curfext.".gif";
                   16842: 	}
                   16843:     }
1.249     albertel 16844:     return &lonhttpdurl($iconname);
1.154     albertel 16845: } 
1.84      albertel 16846: 
1.575     albertel 16847: sub lonhttpdurl {
1.692     www      16848: #
                   16849: # Had been used for "small fry" static images on separate port 8080.
                   16850: # Modify here if lightweight http functionality desired again.
                   16851: # Currently eliminated due to increasing firewall issues.
                   16852: #
1.575     albertel 16853:     my ($url)=@_;
1.692     www      16854:     return $url;
1.215     albertel 16855: }
                   16856: 
1.213     albertel 16857: sub connection_aborted {
                   16858:     my ($r)=@_;
                   16859:     $r->print(" ");$r->rflush();
                   16860:     my $c = $r->connection;
                   16861:     return $c->aborted();
                   16862: }
                   16863: 
1.221     foxr     16864: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16865: #    strings as 'strings'.
                   16866: sub escape_single {
1.221     foxr     16867:     my ($input) = @_;
1.223     albertel 16868:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16869:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16870:     return $input;
                   16871: }
1.223     albertel 16872: 
1.222     foxr     16873: #  Same as escape_single, but escape's "'s  This 
                   16874: #  can be used for  "strings"
                   16875: sub escape_double {
                   16876:     my ($input) = @_;
                   16877:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16878:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16879:     return $input;
                   16880: }
1.223     albertel 16881:  
1.222     foxr     16882: #   Escapes the last element of a full URL.
                   16883: sub escape_url {
                   16884:     my ($url)   = @_;
1.238     raeburn  16885:     my @urlslices = split(/\//, $url,-1);
1.369     www      16886:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16887:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16888: }
1.462     albertel 16889: 
1.820     raeburn  16890: sub compare_arrays {
                   16891:     my ($arrayref1,$arrayref2) = @_;
                   16892:     my (@difference,%count);
                   16893:     @difference = ();
                   16894:     %count = ();
                   16895:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16896:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16897:         foreach my $element (keys(%count)) {
                   16898:             if ($count{$element} == 1) {
                   16899:                 push(@difference,$element);
                   16900:             }
                   16901:         }
                   16902:     }
                   16903:     return @difference;
                   16904: }
                   16905: 
1.1322    raeburn  16906: sub lon_status_items {
                   16907:     my %defaults = (
                   16908:                      E         => 100,
                   16909:                      W         => 4,
                   16910:                      N         => 1,
1.1324    raeburn  16911:                      U         => 5,
1.1322    raeburn  16912:                      threshold => 200,
                   16913:                      sysmail   => 2500,
                   16914:                    );
                   16915:     my %names = (
                   16916:                    E => 'Errors',
                   16917:                    W => 'Warnings',
                   16918:                    N => 'Notices',
1.1324    raeburn  16919:                    U => 'Unsent',
1.1322    raeburn  16920:                 );
                   16921:     return (\%defaults,\%names);
                   16922: }
                   16923: 
1.817     bisitz   16924: # -------------------------------------------------------- Initialize user login
1.462     albertel 16925: sub init_user_environment {
1.463     albertel 16926:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16927:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16928: 
                   16929:     my $public=($username eq 'public' && $domain eq 'public');
                   16930: 
1.1062    raeburn  16931:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16932:     my $now=time;
                   16933: 
                   16934:     if ($public) {
                   16935: 	my $max_public=100;
                   16936: 	my $oldest;
                   16937: 	my $oldest_time=0;
                   16938: 	for(my $next=1;$next<=$max_public;$next++) {
                   16939: 	    if (-e $lonids."/publicuser_$next.id") {
                   16940: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16941: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16942: 		    $oldest_time=$mtime;
                   16943: 		    $oldest=$next;
                   16944: 		}
                   16945: 	    } else {
                   16946: 		$cookie="publicuser_$next";
                   16947: 		last;
                   16948: 	    }
                   16949: 	}
                   16950: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16951:     } else {
1.1275    raeburn  16952: 	# See if old ID present, if so, remove if this isn't a robot,
                   16953: 	# killing any existing non-robot sessions
1.463     albertel 16954: 	if (!$args->{'robot'}) {
                   16955: 	    opendir(DIR,$lonids);
                   16956: 	    while ($filename=readdir(DIR)) {
                   16957: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  16958:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16959:                             &GDBM_READER(),0640)) {
1.1295    raeburn  16960:                         my $linkedfile;
1.1320    raeburn  16961:                         if (exists($oldenv{'user.linkedenv'})) {
                   16962:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  16963:                         }
1.1320    raeburn  16964:                         untie(%oldenv);
                   16965:                         if (unlink("$lonids/$filename")) {
                   16966:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16967:                                 if (-l "$lonids/$linkedfile.id") {
                   16968:                                     unlink("$lonids/$linkedfile.id");
                   16969:                                 }
1.1295    raeburn  16970:                             }
                   16971:                         }
                   16972:                     } else {
                   16973:                         unlink($lonids.'/'.$filename);
                   16974:                     }
1.463     albertel 16975: 		}
1.462     albertel 16976: 	    }
1.463     albertel 16977: 	    closedir(DIR);
1.1204    raeburn  16978: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16979:             my $namespace = 'nohist_courseeditor';
                   16980:             my $lockingkey = 'paste'."\0".'locked_num';
                   16981:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16982:                                                 $domain,$username);
                   16983:             if (exists($lockhash{$lockingkey})) {
                   16984:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16985:                 unless ($delresult eq 'ok') {
                   16986:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16987:                 }
                   16988:             }
1.462     albertel 16989: 	}
                   16990: # Give them a new cookie
1.463     albertel 16991: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16992: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16993: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16994:     
                   16995: # Initialize roles
                   16996: 
1.1062    raeburn  16997: 	($userroles,$firstaccenv,$timerintenv) = 
                   16998:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16999:     }
                   17000: # ------------------------------------ Check browser type and MathML capability
                   17001: 
1.1194    raeburn  17002:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17003:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17004: 
                   17005: # ------------------------------------------------------------- Get environment
                   17006: 
                   17007:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17008:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17009:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17010: 	undef(%userenv);
                   17011:     }
                   17012:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17013: 	$form->{'interface'}=$userenv{'interface'};
                   17014:     }
                   17015:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17016: 
                   17017: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17018:     foreach my $option ('interface','localpath','localres') {
                   17019:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17020:     }
                   17021: # --------------------------------------------------------- Write first profile
                   17022: 
                   17023:     {
1.1350    raeburn  17024:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17025: 	my %initial_env = 
                   17026: 	    ("user.name"          => $username,
                   17027: 	     "user.domain"        => $domain,
                   17028: 	     "user.home"          => $authhost,
                   17029: 	     "browser.type"       => $clientbrowser,
                   17030: 	     "browser.version"    => $clientversion,
                   17031: 	     "browser.mathml"     => $clientmathml,
                   17032: 	     "browser.unicode"    => $clientunicode,
                   17033: 	     "browser.os"         => $clientos,
1.1137    raeburn  17034:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17035:              "browser.info"       => $clientinfo,
1.1194    raeburn  17036:              "browser.osversion"  => $clientosversion,
1.462     albertel 17037: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17038: 	     "request.course.fn"  => '',
                   17039: 	     "request.course.uri" => '',
                   17040: 	     "request.course.sec" => '',
                   17041: 	     "request.role"       => 'cm',
                   17042: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17043: 	     "request.host"       => $ip,);
1.462     albertel 17044: 
                   17045:         if ($form->{'localpath'}) {
                   17046: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17047: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17048:         }
                   17049: 	
                   17050: 	if ($form->{'interface'}) {
                   17051: 	    $form->{'interface'}=~s/\W//gs;
                   17052: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17053: 	    $env{'browser.interface'}=$form->{'interface'};
                   17054: 	}
                   17055: 
1.1157    raeburn  17056:         if ($form->{'iptoken'}) {
                   17057:             my $lonhost = $r->dir_config('lonHostID');
                   17058:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17059:             $env{'user.noloadbalance'} = $lonhost;
                   17060:         }
                   17061: 
1.1268    raeburn  17062:         if ($form->{'noloadbalance'}) {
                   17063:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17064:             my $hosthere = $form->{'noloadbalance'};
                   17065:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17066:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17067:                 $env{'user.noloadbalance'} = $hosthere;
                   17068:             }
                   17069:         }
                   17070: 
1.1016    raeburn  17071:         unless ($domain eq 'public') {
1.1273    raeburn  17072:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17073:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17074: 
                   17075:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   17076:                 $userenv{'availabletools.'.$tool} = 
                   17077:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17078:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17079:             }
1.980     raeburn  17080: 
1.1311    raeburn  17081:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17082:                 $userenv{'canrequest.'.$crstype} =
                   17083:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17084:                                                       'reload','requestcourses',
                   17085:                                                       \%userenv,\%domdef,\%is_adv);
                   17086:             }
1.724     raeburn  17087: 
1.1273    raeburn  17088:             $userenv{'canrequest.author'} =
                   17089:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17090:                                                   'reload','requestauthor',
1.980     raeburn  17091:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17092:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17093:                                                  $domain,$username);
                   17094:             my $reqstatus = $reqauthor{'author_status'};
                   17095:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17096:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17097:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17098:                                                       $reqauthor{'author'}{'timestamp'};
                   17099:                 }
1.1092    raeburn  17100:             }
1.1287    raeburn  17101:             my ($types,$typename) = &course_types();
                   17102:             if (ref($types) eq 'ARRAY') {
                   17103:                 my @options = ('approval','validate','autolimit');
                   17104:                 my $optregex = join('|',@options);
                   17105:                 my (%willtrust,%trustchecked);
                   17106:                 foreach my $type (@{$types}) {
                   17107:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17108:                     if ($dom_str ne '') {
                   17109:                         my $updatedstr = '';
                   17110:                         my @possdomains = split(',',$dom_str);
                   17111:                         foreach my $entry (@possdomains) {
                   17112:                             my ($extdom,$extopt) = split(':',$entry);
                   17113:                             unless ($trustchecked{$extdom}) {
                   17114:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17115:                                 $trustchecked{$extdom} = 1;
                   17116:                             }
                   17117:                             if ($willtrust{$extdom}) {
                   17118:                                 $updatedstr .= $entry.',';
                   17119:                             }
                   17120:                         }
                   17121:                         $updatedstr =~ s/,$//;
                   17122:                         if ($updatedstr) {
                   17123:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17124:                         } else {
                   17125:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17126:                         }
                   17127:                     }
                   17128:                 }
                   17129:             }
1.1092    raeburn  17130:         }
1.462     albertel 17131: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17132: 
1.462     albertel 17133: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17134: 		 &GDBM_WRCREAT(),0640)) {
                   17135: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17136: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17137: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17138:             if (ref($firstaccenv) eq 'HASH') {
                   17139:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17140:             }
                   17141:             if (ref($timerintenv) eq 'HASH') {
                   17142:                 &_add_to_env(\%disk_env,$timerintenv);
                   17143:             }
1.463     albertel 17144: 	    if (ref($args->{'extra_env'})) {
                   17145: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17146: 	    }
1.462     albertel 17147: 	    untie(%disk_env);
                   17148: 	} else {
1.705     tempelho 17149: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17150: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17151: 	    return 'error: '.$!;
                   17152: 	}
                   17153:     }
                   17154:     $env{'request.role'}='cm';
                   17155:     $env{'request.role.adv'}=$env{'user.adv'};
                   17156:     $env{'browser.type'}=$clientbrowser;
                   17157: 
                   17158:     return $cookie;
                   17159: 
                   17160: }
                   17161: 
                   17162: sub _add_to_env {
                   17163:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17164:     if (ref($env_data) eq 'HASH') {
                   17165:         while (my ($key,$value) = each(%$env_data)) {
                   17166: 	    $idf->{$prefix.$key} = $value;
                   17167: 	    $env{$prefix.$key}   = $value;
                   17168:         }
1.462     albertel 17169:     }
                   17170: }
                   17171: 
1.685     tempelho 17172: # --- Get the symbolic name of a problem and the url
                   17173: sub get_symb {
                   17174:     my ($request,$silent) = @_;
1.726     raeburn  17175:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17176:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17177:     if ($symb eq '') {
                   17178:         if (!$silent) {
1.1071    raeburn  17179:             if (ref($request)) { 
                   17180:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17181:             }
1.685     tempelho 17182:             return ();
                   17183:         }
                   17184:     }
                   17185:     &Apache::lonenc::check_decrypt(\$symb);
                   17186:     return ($symb);
                   17187: }
                   17188: 
                   17189: # --------------------------------------------------------------Get annotation
                   17190: 
                   17191: sub get_annotation {
                   17192:     my ($symb,$enc) = @_;
                   17193: 
                   17194:     my $key = $symb;
                   17195:     if (!$enc) {
                   17196:         $key =
                   17197:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17198:     }
                   17199:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17200:     return $annotation{$key};
                   17201: }
                   17202: 
                   17203: sub clean_symb {
1.731     raeburn  17204:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17205: 
                   17206:     &Apache::lonenc::check_decrypt(\$symb);
                   17207:     my $enc = $env{'request.enc'};
1.731     raeburn  17208:     if ($delete_enc) {
1.730     raeburn  17209:         delete($env{'request.enc'});
                   17210:     }
1.685     tempelho 17211: 
                   17212:     return ($symb,$enc);
                   17213: }
1.462     albertel 17214: 
1.1181    raeburn  17215: ############################################################
                   17216: ############################################################
                   17217: 
                   17218: =pod
                   17219: 
                   17220: =head1 Routines for building display used to search for courses
                   17221: 
                   17222: 
                   17223: =over 4
                   17224: 
                   17225: =item * &build_filters()
                   17226: 
                   17227: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17228: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17229: and quotacheck.pl
                   17230: 
1.1181    raeburn  17231: 
                   17232: Inputs:
                   17233: 
                   17234: filterlist - anonymous array of fields to include as potential filters 
                   17235: 
                   17236: crstype - course type
                   17237: 
                   17238: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17239:               to pop-open a course selector (will contain "extra element"). 
                   17240: 
                   17241: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17242: 
                   17243: filter - anonymous hash of criteria and their values
                   17244: 
                   17245: action - form action
                   17246: 
                   17247: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17248: 
1.1182    raeburn  17249: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17250: 
                   17251: cloneruname - username of owner of new course who wants to clone
                   17252: 
                   17253: clonerudom - domain of owner of new course who wants to clone
                   17254: 
                   17255: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17256: 
                   17257: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17258: 
                   17259: codedom - domain
                   17260: 
                   17261: formname - value of form element named "form". 
                   17262: 
                   17263: fixeddom - domain, if fixed.
                   17264: 
                   17265: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17266: 
                   17267: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17268: 
                   17269: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17270: 
                   17271: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17272: 
                   17273: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17274: 
                   17275: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17276: 
                   17277: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17278: 
1.1182    raeburn  17279: 
1.1181    raeburn  17280: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17281: 
1.1182    raeburn  17282: 
1.1181    raeburn  17283: Side Effects: None
                   17284: 
                   17285: =cut
                   17286: 
                   17287: # ---------------------------------------------- search for courses based on last activity etc.
                   17288: 
                   17289: sub build_filters {
                   17290:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17291:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17292:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17293:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17294:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17295:     my ($list,$jscript);
1.1181    raeburn  17296:     my $onchange = 'javascript:updateFilters(this)';
                   17297:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17298:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17299:         $typeselectform,$instcodetitle);
                   17300:     if ($formname eq '') {
                   17301:         $formname = $caller;
                   17302:     }
                   17303:     foreach my $item (@{$filterlist}) {
                   17304:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17305:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17306:             if ($item eq 'domainfilter') {
                   17307:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17308:             } elsif ($item eq 'coursefilter') {
                   17309:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17310:             } elsif ($item eq 'ownerfilter') {
                   17311:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17312:             } elsif ($item eq 'ownerdomfilter') {
                   17313:                 $filter->{'ownerdomfilter'} =
                   17314:                     &LONCAPA::clean_domain($filter->{$item});
                   17315:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17316:                                                        'ownerdomfilter',1);
                   17317:             } elsif ($item eq 'personfilter') {
                   17318:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17319:             } elsif ($item eq 'persondomfilter') {
                   17320:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17321:                                                         'persondomfilter',1);
                   17322:             } else {
                   17323:                 $filter->{$item} =~ s/\W//g;
                   17324:             }
                   17325:             if (!$filter->{$item}) {
                   17326:                 $filter->{$item} = '';
                   17327:             }
                   17328:         }
                   17329:         if ($item eq 'domainfilter') {
                   17330:             my $allow_blank = 1;
                   17331:             if ($formname eq 'portform') {
                   17332:                 $allow_blank=0;
                   17333:             } elsif ($formname eq 'studentform') {
                   17334:                 $allow_blank=0;
                   17335:             }
                   17336:             if ($fixeddom) {
                   17337:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17338:                                     ' value="'.$codedom.'" />'.
                   17339:                                     &Apache::lonnet::domain($codedom,'description');
                   17340:             } else {
                   17341:                 $domainselectform = &select_dom_form($filter->{$item},
                   17342:                                                      'domainfilter',
                   17343:                                                       $allow_blank,'',$onchange);
                   17344:             }
                   17345:         } else {
                   17346:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17347:         }
                   17348:     }
                   17349: 
                   17350:     # last course activity filter and selection
                   17351:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17352: 
                   17353:     # course created filter and selection
                   17354:     if (exists($filter->{'createdfilter'})) {
                   17355:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17356:     }
                   17357: 
1.1239    raeburn  17358:     my $prefix = $crstype;
                   17359:     if ($crstype eq 'Placement') {
                   17360:         $prefix = 'Placement Test'
                   17361:     }
1.1181    raeburn  17362:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17363:                 'cac' => "$prefix Activity",
                   17364:                 'ccr' => "$prefix Created",
                   17365:                 'cde' => "$prefix Title",
                   17366:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17367:                 'ins' => 'Institutional Code',
                   17368:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17369:                 'cow' => "$prefix Owner/Co-owner",
                   17370:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17371:                 'cog' => 'Type',
                   17372:              );
                   17373: 
                   17374:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17375:         my $typeval = 'Course';
                   17376:         if ($crstype eq 'Community') {
                   17377:             $typeval = 'Community';
1.1239    raeburn  17378:         } elsif ($crstype eq 'Placement') {
                   17379:             $typeval = 'Placement';
1.1181    raeburn  17380:         }
                   17381:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17382:     } else {
                   17383:         $typeselectform =  '<select name="type" size="1"';
                   17384:         if ($onchange) {
                   17385:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17386:         }
                   17387:         $typeselectform .= '>'."\n";
1.1237    raeburn  17388:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17389:             my $shown;
                   17390:             if ($posstype eq 'Placement') {
                   17391:                 $shown = &mt('Placement Test');
                   17392:             } else {
                   17393:                 $shown = &mt($posstype);
                   17394:             }
1.1181    raeburn  17395:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17396:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17397:         }
                   17398:         $typeselectform.="</select>";
                   17399:     }
                   17400: 
                   17401:     my ($cloneableonlyform,$cloneabletitle);
                   17402:     if (exists($filter->{'cloneableonly'})) {
                   17403:         my $cloneableon = '';
                   17404:         my $cloneableoff = ' checked="checked"';
                   17405:         if ($filter->{'cloneableonly'}) {
                   17406:             $cloneableon = $cloneableoff;
                   17407:             $cloneableoff = '';
                   17408:         }
                   17409:         $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>';
                   17410:         if ($formname eq 'ccrs') {
1.1187    bisitz   17411:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17412:         } else {
                   17413:             $cloneabletitle = &mt('Cloneable by you');
                   17414:         }
                   17415:     }
                   17416:     my $officialjs;
                   17417:     if ($crstype eq 'Course') {
                   17418:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17419: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17420: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17421:             if ($codedom) { 
1.1181    raeburn  17422:                 $officialjs = 1;
                   17423:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17424:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17425:                                                                   $officialjs,$codetitlesref);
                   17426:                 if ($jscript) {
1.1182    raeburn  17427:                     $jscript = '<script type="text/javascript">'."\n".
                   17428:                                '// <![CDATA['."\n".
                   17429:                                $jscript."\n".
                   17430:                                '// ]]>'."\n".
                   17431:                                '</script>'."\n";
1.1181    raeburn  17432:                 }
                   17433:             }
                   17434:             if ($instcodeform eq '') {
                   17435:                 $instcodeform =
                   17436:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17437:                     $list->{'instcodefilter'}.'" />';
                   17438:                 $instcodetitle = $lt{'ins'};
                   17439:             } else {
                   17440:                 $instcodetitle = $lt{'inc'};
                   17441:             }
                   17442:             if ($fixeddom) {
                   17443:                 $instcodetitle .= '<br />('.$codedom.')';
                   17444:             }
                   17445:         }
                   17446:     }
                   17447:     my $output = qq|
                   17448: <form method="post" name="filterpicker" action="$action">
                   17449: <input type="hidden" name="form" value="$formname" />
                   17450: |;
                   17451:     if ($formname eq 'modifycourse') {
                   17452:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17453:                    '<input type="hidden" name="prevphase" value="'.
                   17454:                    $prevphase.'" />'."\n";
1.1198    musolffc 17455:     } elsif ($formname eq 'quotacheck') {
                   17456:         $output .= qq|
                   17457: <input type="hidden" name="sortby" value="" />
                   17458: <input type="hidden" name="sortorder" value="" />
                   17459: |;
                   17460:     } else {
1.1181    raeburn  17461:         my $name_input;
                   17462:         if ($cnameelement ne '') {
                   17463:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17464:                           $cnameelement.'" />';
                   17465:         }
                   17466:         $output .= qq|
1.1182    raeburn  17467: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17468: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17469: $name_input
                   17470: $roleelement
                   17471: $multelement
                   17472: $typeelement
                   17473: |;
                   17474:         if ($formname eq 'portform') {
                   17475:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17476:         }
                   17477:     }
                   17478:     if ($fixeddom) {
                   17479:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17480:     }
                   17481:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17482:     if ($sincefilterform) {
                   17483:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17484:                   .$sincefilterform
                   17485:                   .&Apache::lonhtmlcommon::row_closure();
                   17486:     }
                   17487:     if ($createdfilterform) {
                   17488:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17489:                   .$createdfilterform
                   17490:                   .&Apache::lonhtmlcommon::row_closure();
                   17491:     }
                   17492:     if ($domainselectform) {
                   17493:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17494:                   .$domainselectform
                   17495:                   .&Apache::lonhtmlcommon::row_closure();
                   17496:     }
                   17497:     if ($typeselectform) {
                   17498:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17499:             $output .= $typeselectform;
                   17500:         } else {
                   17501:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17502:                       .$typeselectform
                   17503:                       .&Apache::lonhtmlcommon::row_closure();
                   17504:         }
                   17505:     }
                   17506:     if ($instcodeform) {
                   17507:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17508:                   .$instcodeform
                   17509:                   .&Apache::lonhtmlcommon::row_closure();
                   17510:     }
                   17511:     if (exists($filter->{'ownerfilter'})) {
                   17512:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17513:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17514:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17515:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17516:                    $ownerdomselectform.'</td></tr></table>'.
                   17517:                    &Apache::lonhtmlcommon::row_closure();
                   17518:     }
                   17519:     if (exists($filter->{'personfilter'})) {
                   17520:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17521:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17522:                    '<input type="text" name="personfilter" size="20" value="'.
                   17523:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17524:                    $persondomselectform.'</td></tr></table>'.
                   17525:                    &Apache::lonhtmlcommon::row_closure();
                   17526:     }
                   17527:     if (exists($filter->{'coursefilter'})) {
                   17528:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17529:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17530:                   .$list->{'coursefilter'}.'" />'
                   17531:                   .&Apache::lonhtmlcommon::row_closure();
                   17532:     }
                   17533:     if ($cloneableonlyform) {
                   17534:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17535:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17536:     }
                   17537:     if (exists($filter->{'descriptfilter'})) {
                   17538:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17539:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17540:                   .$list->{'descriptfilter'}.'" />'
                   17541:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17542:     }
                   17543:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17544:                '<input type="hidden" name="updater" value="" />'."\n".
                   17545:                '<input type="submit" name="gosearch" value="'.
                   17546:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17547:     return $jscript.$clonewarning.$output;
                   17548: }
                   17549: 
                   17550: =pod 
                   17551: 
                   17552: =item * &timebased_select_form()
                   17553: 
1.1182    raeburn  17554: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17555: filter e.g., Course Activity, Course Created, when searching for courses
                   17556: or communities
                   17557: 
                   17558: Inputs:
                   17559: 
                   17560: item - name of form element (sincefilter or createdfilter)
                   17561: 
                   17562: filter - anonymous hash of criteria and their values
                   17563: 
                   17564: Returns: HTML for a select box contained a blank, then six time selections,
                   17565:          with value set in incoming form variables currently selected. 
                   17566: 
                   17567: Side Effects: None
                   17568: 
                   17569: =cut
                   17570: 
                   17571: sub timebased_select_form {
                   17572:     my ($item,$filter) = @_;
                   17573:     if (ref($filter) eq 'HASH') {
                   17574:         $filter->{$item} =~ s/[^\d-]//g;
                   17575:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17576:         return &select_form(
                   17577:                             $filter->{$item},
                   17578:                             $item,
                   17579:                             {      '-1' => '',
                   17580:                                 '86400' => &mt('today'),
                   17581:                                '604800' => &mt('last week'),
                   17582:                               '2592000' => &mt('last month'),
                   17583:                               '7776000' => &mt('last three months'),
                   17584:                              '15552000' => &mt('last six months'),
                   17585:                              '31104000' => &mt('last year'),
                   17586:                     'select_form_order' =>
                   17587:                            ['-1','86400','604800','2592000','7776000',
                   17588:                             '15552000','31104000']});
                   17589:     }
                   17590: }
                   17591: 
                   17592: =pod
                   17593: 
                   17594: =item * &js_changer()
                   17595: 
                   17596: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17597: when course type or domain is changed, and also to hide 'Searching ...' on
                   17598: page load completion for page showing search result.
1.1181    raeburn  17599: 
                   17600: Inputs: None
                   17601: 
1.1183    raeburn  17602: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17603: 
                   17604: Side Effects: None
                   17605: 
                   17606: =cut
                   17607: 
                   17608: sub js_changer {
                   17609:     return <<ENDJS;
                   17610: <script type="text/javascript">
                   17611: // <![CDATA[
                   17612: function updateFilters(caller) {
                   17613:     if (typeof(caller) != "undefined") {
                   17614:         document.filterpicker.updater.value = caller.name;
                   17615:     }
                   17616:     document.filterpicker.submit();
                   17617: }
1.1183    raeburn  17618: 
                   17619: function hideSearching() {
                   17620:     if (document.getElementById('searching')) {
                   17621:         document.getElementById('searching').style.display = 'none';
                   17622:     }
                   17623:     return;
                   17624: }
                   17625: 
1.1181    raeburn  17626: // ]]>
                   17627: </script>
                   17628: 
                   17629: ENDJS
                   17630: }
                   17631: 
                   17632: =pod
                   17633: 
1.1182    raeburn  17634: =item * &search_courses()
                   17635: 
                   17636: Process selected filters form course search form and pass to lonnet::courseiddump
                   17637: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17638: 
                   17639: Inputs:
                   17640: 
                   17641: dom - domain being searched 
                   17642: 
                   17643: type - course type ('Course' or 'Community' or '.' if any).
                   17644: 
                   17645: filter - anonymous hash of criteria and their values
                   17646: 
                   17647: numtitles - for institutional codes - number of categories
                   17648: 
                   17649: cloneruname - optional username of new course owner
                   17650: 
                   17651: clonerudom - optional domain of new course owner
                   17652: 
1.1221    raeburn  17653: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17654:             (used when DC is using course creation form)
                   17655: 
                   17656: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17657: 
1.1221    raeburn  17658: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17659:            (and so can clone automatically)
                   17660: 
                   17661: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17662: 
                   17663: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17664:               courses to clone 
1.1182    raeburn  17665: 
                   17666: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17667: 
                   17668: 
                   17669: Side Effects: None
                   17670: 
                   17671: =cut
                   17672: 
                   17673: 
                   17674: sub search_courses {
1.1221    raeburn  17675:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17676:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17677:     my (%courses,%showcourses,$cloner);
                   17678:     if (($filter->{'ownerfilter'} ne '') ||
                   17679:         ($filter->{'ownerdomfilter'} ne '')) {
                   17680:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17681:                                        $filter->{'ownerdomfilter'};
                   17682:     }
                   17683:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17684:         if (!$filter->{$item}) {
                   17685:             $filter->{$item}='.';
                   17686:         }
                   17687:     }
                   17688:     my $now = time;
                   17689:     my $timefilter =
                   17690:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17691:     my ($createdbefore,$createdafter);
                   17692:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17693:         $createdbefore = $now;
                   17694:         $createdafter = $now-$filter->{'createdfilter'};
                   17695:     }
                   17696:     my ($instcodefilter,$regexpok);
                   17697:     if ($numtitles) {
                   17698:         if ($env{'form.official'} eq 'on') {
                   17699:             $instcodefilter =
                   17700:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17701:             $regexpok = 1;
                   17702:         } elsif ($env{'form.official'} eq 'off') {
                   17703:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17704:             unless ($instcodefilter eq '') {
                   17705:                 $regexpok = -1;
                   17706:             }
                   17707:         }
                   17708:     } else {
                   17709:         $instcodefilter = $filter->{'instcodefilter'};
                   17710:     }
                   17711:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17712:     if ($type eq '') { $type = '.'; }
                   17713: 
                   17714:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17715:         $cloner = $cloneruname.':'.$clonerudom;
                   17716:     }
                   17717:     %courses = &Apache::lonnet::courseiddump($dom,
                   17718:                                              $filter->{'descriptfilter'},
                   17719:                                              $timefilter,
                   17720:                                              $instcodefilter,
                   17721:                                              $filter->{'combownerfilter'},
                   17722:                                              $filter->{'coursefilter'},
                   17723:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17724:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17725:                                              $filter->{'cloneableonly'},
                   17726:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17727:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17728:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17729:         my $ccrole;
                   17730:         if ($type eq 'Community') {
                   17731:             $ccrole = 'co';
                   17732:         } else {
                   17733:             $ccrole = 'cc';
                   17734:         }
                   17735:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17736:                                                      $filter->{'persondomfilter'},
                   17737:                                                      'userroles',undef,
                   17738:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17739:                                                      $dom);
                   17740:         foreach my $role (keys(%rolehash)) {
                   17741:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17742:             my $cid = $cdom.'_'.$cnum;
                   17743:             if (exists($courses{$cid})) {
                   17744:                 if (ref($courses{$cid}) eq 'HASH') {
                   17745:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17746:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17747:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17748:                         }
                   17749:                     } else {
                   17750:                         $courses{$cid}{roles} = [$courserole];
                   17751:                     }
                   17752:                     $showcourses{$cid} = $courses{$cid};
                   17753:                 }
                   17754:             }
                   17755:         }
                   17756:         %courses = %showcourses;
                   17757:     }
                   17758:     return %courses;
                   17759: }
                   17760: 
                   17761: =pod
                   17762: 
1.1181    raeburn  17763: =back
                   17764: 
1.1207    raeburn  17765: =head1 Routines for version requirements for current course.
                   17766: 
                   17767: =over 4
                   17768: 
                   17769: =item * &check_release_required()
                   17770: 
                   17771: Compares required LON-CAPA version with version on server, and
                   17772: if required version is newer looks for a server with the required version.
                   17773: 
                   17774: Looks first at servers in user's owen domain; if none suitable, looks at
                   17775: servers in course's domain are permitted to host sessions for user's domain.
                   17776: 
                   17777: Inputs:
                   17778: 
                   17779: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17780: 
                   17781: $courseid - Course ID of current course
                   17782: 
                   17783: $rolecode - User's current role in course (for switchserver query string).
                   17784: 
                   17785: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17786: 
                   17787: 
                   17788: Returns:
                   17789: 
                   17790: $switchserver - query string tp append to /adm/switchserver call (if 
                   17791:                 current server's LON-CAPA version is too old. 
                   17792: 
                   17793: $warning - Message is displayed if no suitable server could be found.
                   17794: 
                   17795: =cut
                   17796: 
                   17797: sub check_release_required {
                   17798:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17799:     my ($switchserver,$warning);
                   17800:     if ($required ne '') {
                   17801:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17802:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17803:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17804:             my $otherserver;
                   17805:             if (($major eq '' && $minor eq '') ||
                   17806:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17807:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17808:                 my $switchlcrev =
                   17809:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17810:                                                            $userdomserver);
                   17811:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17812:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17813:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17814:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17815:                     if ($cdom ne $env{'user.domain'}) {
                   17816:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17817:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17818:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17819:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17820:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17821:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17822:                         my $canhost =
                   17823:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17824:                                                               $coursedomserver,
                   17825:                                                               $remoterev,
                   17826:                                                               $udomdefaults{'remotesessions'},
                   17827:                                                               $defdomdefaults{'hostedsessions'});
                   17828: 
                   17829:                         if ($canhost) {
                   17830:                             $otherserver = $coursedomserver;
                   17831:                         } else {
                   17832:                             $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.");
                   17833:                         }
                   17834:                     } else {
                   17835:                         $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).");
                   17836:                     }
                   17837:                 } else {
                   17838:                     $otherserver = $userdomserver;
                   17839:                 }
                   17840:             }
                   17841:             if ($otherserver ne '') {
                   17842:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17843:             }
                   17844:         }
                   17845:     }
                   17846:     return ($switchserver,$warning);
                   17847: }
                   17848: 
                   17849: =pod
                   17850: 
                   17851: =item * &check_release_result()
                   17852: 
                   17853: Inputs:
                   17854: 
                   17855: $switchwarning - Warning message if no suitable server found to host session.
                   17856: 
                   17857: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17858:                 and current role.
                   17859: 
                   17860: Returns: HTML to display with information about requirement to switch server.
                   17861:          Either displaying warning with link to Roles/Courses screen or
                   17862:          display link to switchserver.
                   17863: 
1.1181    raeburn  17864: =cut
                   17865: 
1.1207    raeburn  17866: sub check_release_result {
                   17867:     my ($switchwarning,$switchserver) = @_;
                   17868:     my $output = &start_page('Selected course unavailable on this server').
                   17869:                  '<p class="LC_warning">';
                   17870:     if ($switchwarning) {
                   17871:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17872:         if (&show_course()) {
                   17873:             $output .= &mt('Display courses');
                   17874:         } else {
                   17875:             $output .= &mt('Display roles');
                   17876:         }
                   17877:         $output .= '</a>';
                   17878:     } elsif ($switchserver) {
                   17879:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17880:                    '<br />'.
                   17881:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17882:                    &mt('Switch Server').
                   17883:                    '</a>';
                   17884:     }
                   17885:     $output .= '</p>'.&end_page();
                   17886:     return $output;
                   17887: }
                   17888: 
                   17889: =pod
                   17890: 
                   17891: =item * &needs_coursereinit()
                   17892: 
                   17893: Determine if course contents stored for user's session needs to be
                   17894: refreshed, because content has changed since "Big Hash" last tied.
                   17895: 
                   17896: Check for change is made if time last checked is more than 10 minutes ago
                   17897: (by default).
                   17898: 
                   17899: Inputs:
                   17900: 
                   17901: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17902: 
                   17903: $interval (optional) - Time which may elapse (in s) between last check for content
                   17904:                        change in current course. (default: 600 s).  
                   17905: 
                   17906: Returns: an array; first element is:
                   17907: 
                   17908: =over 4
                   17909: 
                   17910: 'switch' - if content updates mean user's session
                   17911:            needs to be switched to a server running a newer LON-CAPA version
                   17912:  
                   17913: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17914:            on current server hosting user's session                
                   17915: 
                   17916: ''       - if no action required.
                   17917: 
                   17918: =back
                   17919: 
                   17920: If first item element is 'switch':
                   17921: 
                   17922: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17923: 
                   17924: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17925:                               and current role. 
                   17926: 
                   17927: otherwise: no other elements returned.
                   17928: 
                   17929: =back
                   17930: 
                   17931: =cut
                   17932: 
                   17933: sub needs_coursereinit {
                   17934:     my ($loncaparev,$interval) = @_;
                   17935:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17936:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17937:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17938:     my $now = time;
                   17939:     if ($interval eq '') {
                   17940:         $interval = 600;
                   17941:     }
                   17942:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17943:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17944:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17945:         if ($blocked) {
                   17946:             return ();
                   17947:         }
1.1207    raeburn  17948:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17949:         if ($lastchange > $env{'request.course.tied'}) {
                   17950:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17951:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17952:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17953:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17954:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17955:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17956:                     my ($switchserver,$switchwarning) =
                   17957:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17958:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17959:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17960:                         return ('switch',$switchwarning,$switchserver);
                   17961:                     }
                   17962:                 }
                   17963:             }
                   17964:             return ('update');
                   17965:         }
                   17966:     }
                   17967:     return ();
                   17968: }
1.1181    raeburn  17969: 
1.1083    raeburn  17970: sub update_content_constraints {
1.1326    raeburn  17971:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  17972:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17973:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  17974:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  17975:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17976:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17977:         if ($item eq 'resourcetag') {
                   17978:             if ($name eq 'responsetype') {
                   17979:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17980:             }
1.1307    raeburn  17981:         } elsif ($item eq 'course') {
                   17982:             if ($name eq 'courserestype') {
                   17983:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   17984:             }
1.1083    raeburn  17985:         }
                   17986:     }
                   17987:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17988:     if (defined($navmap)) {
1.1307    raeburn  17989:         my (%allresponses,%allcrsrestypes);
                   17990:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   17991:             if ($res->is_tool()) {
                   17992:                 if ($allcrsrestypes{'exttool'}) {
                   17993:                     $allcrsrestypes{'exttool'} ++;
                   17994:                 } else {
                   17995:                     $allcrsrestypes{'exttool'} = 1;
                   17996:                 }
                   17997:                 next;
                   17998:             }
1.1083    raeburn  17999:             my %responses = $res->responseTypes();
                   18000:             foreach my $key (keys(%responses)) {
                   18001:                 next unless(exists($checkresponsetypes{$key}));
                   18002:                 $allresponses{$key} += $responses{$key};
                   18003:             }
                   18004:         }
                   18005:         foreach my $key (keys(%allresponses)) {
                   18006:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18007:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18008:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18009:             }
                   18010:         }
1.1307    raeburn  18011:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18012:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18013:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18014:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18015:             }
                   18016:         }
1.1083    raeburn  18017:         undef($navmap);
                   18018:     }
1.1326    raeburn  18019:     my (@resources,@order,@resparms,@zombies);
                   18020:     if ($keeporder) {
                   18021:         use LONCAPA::map;
                   18022:         @resources = @LONCAPA::map::resources;
                   18023:         @order = @LONCAPA::map::order;
                   18024:         @resparms = @LONCAPA::map::resparms;
                   18025:         @zombies = @LONCAPA::map::zombies;
                   18026:     }
1.1308    raeburn  18027:     my $suppmap = 'supplemental.sequence';
                   18028:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   18029:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   18030:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  18031:     if ($keeporder) {
                   18032:         @LONCAPA::map::resources = @resources;
                   18033:         @LONCAPA::map::order = @order;
                   18034:         @LONCAPA::map::resparms = @resparms;
                   18035:         @LONCAPA::map::zombies = @zombies;
                   18036:     }
1.1308    raeburn  18037:     if ($supptools) {
                   18038:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18039:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18040:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18041:         }
                   18042:     }
1.1083    raeburn  18043:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18044:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18045:     }
                   18046:     return;
                   18047: }
                   18048: 
1.1110    raeburn  18049: sub allmaps_incourse {
                   18050:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18051:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18052:         $cid = $env{'request.course.id'};
                   18053:         $cdom = $env{'course.'.$cid.'.domain'};
                   18054:         $cnum = $env{'course.'.$cid.'.num'};
                   18055:         $chome = $env{'course.'.$cid.'.home'};
                   18056:     }
                   18057:     my %allmaps = ();
                   18058:     my $lastchange =
                   18059:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18060:     if ($lastchange > $env{'request.course.tied'}) {
                   18061:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18062:         unless ($ferr) {
1.1326    raeburn  18063:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  18064:         }
                   18065:     }
                   18066:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18067:     if (defined($navmap)) {
                   18068:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18069:             $allmaps{$res->src()} = 1;
                   18070:         }
                   18071:     }
                   18072:     return \%allmaps;
                   18073: }
                   18074: 
1.1083    raeburn  18075: sub parse_supplemental_title {
                   18076:     my ($title) = @_;
                   18077: 
                   18078:     my ($foldertitle,$renametitle);
                   18079:     if ($title =~ /&amp;&amp;&amp;/) {
                   18080:         $title = &HTML::Entites::decode($title);
                   18081:     }
                   18082:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18083:         $renametitle=$4;
                   18084:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18085:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18086:         my $name =  &plainname($uname,$udom);
                   18087:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18088:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18089:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18090:             $name.': <br />'.$foldertitle;
                   18091:     }
                   18092:     if (wantarray) {
                   18093:         return ($title,$foldertitle,$renametitle);
                   18094:     }
                   18095:     return $title;
                   18096: }
                   18097: 
1.1143    raeburn  18098: sub recurse_supplemental {
1.1308    raeburn  18099:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  18100:     if ($suppmap) {
                   18101:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18102:         if ($fatal) {
                   18103:             $errors ++;
                   18104:         } else {
                   18105:             if ($#LONCAPA::map::resources > 0) {
                   18106:                 foreach my $res (@LONCAPA::map::resources) {
                   18107:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   18108:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  18109:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  18110:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   18111:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  18112:                         } else {
1.1308    raeburn  18113:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   18114:                                 $numexttools ++;
                   18115:                             }
1.1143    raeburn  18116:                             $numfiles ++;
                   18117:                         }
                   18118:                     }
                   18119:                 }
                   18120:             }
                   18121:         }
                   18122:     }
1.1308    raeburn  18123:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  18124: }
                   18125: 
1.1101    raeburn  18126: sub symb_to_docspath {
1.1267    raeburn  18127:     my ($symb,$navmapref) = @_;
                   18128:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18129:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18130:     if ($resurl=~/\.(sequence|page)$/) {
                   18131:         $mapurl=$resurl;
                   18132:     } elsif ($resurl eq 'adm/navmaps') {
                   18133:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18134:     }
                   18135:     my $mapresobj;
1.1267    raeburn  18136:     unless (ref($$navmapref)) {
                   18137:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18138:     }
                   18139:     if (ref($$navmapref)) {
                   18140:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18141:     }
                   18142:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18143:     my $type=$2;
                   18144:     my $path;
                   18145:     if (ref($mapresobj)) {
                   18146:         my $pcslist = $mapresobj->map_hierarchy();
                   18147:         if ($pcslist ne '') {
                   18148:             foreach my $pc (split(/,/,$pcslist)) {
                   18149:                 next if ($pc <= 1);
1.1267    raeburn  18150:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18151:                 if (ref($res)) {
                   18152:                     my $thisurl = $res->src();
                   18153:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18154:                     my $thistitle = $res->title();
                   18155:                     $path .= '&'.
                   18156:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18157:                              &escape($thistitle).
1.1101    raeburn  18158:                              ':'.$res->randompick().
                   18159:                              ':'.$res->randomout().
                   18160:                              ':'.$res->encrypted().
                   18161:                              ':'.$res->randomorder().
                   18162:                              ':'.$res->is_page();
                   18163:                 }
                   18164:             }
                   18165:         }
                   18166:         $path =~ s/^\&//;
                   18167:         my $maptitle = $mapresobj->title();
                   18168:         if ($mapurl eq 'default') {
1.1129    raeburn  18169:             $maptitle = 'Main Content';
1.1101    raeburn  18170:         }
                   18171:         $path .= (($path ne '')? '&' : '').
                   18172:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18173:                  &escape($maptitle).
1.1101    raeburn  18174:                  ':'.$mapresobj->randompick().
                   18175:                  ':'.$mapresobj->randomout().
                   18176:                  ':'.$mapresobj->encrypted().
                   18177:                  ':'.$mapresobj->randomorder().
                   18178:                  ':'.$mapresobj->is_page();
                   18179:     } else {
                   18180:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18181:         my $ispage = (($type eq 'page')? 1 : '');
                   18182:         if ($mapurl eq 'default') {
1.1129    raeburn  18183:             $maptitle = 'Main Content';
1.1101    raeburn  18184:         }
                   18185:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18186:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18187:     }
                   18188:     unless ($mapurl eq 'default') {
                   18189:         $path = 'default&'.
1.1146    raeburn  18190:                 &escape('Main Content').
1.1101    raeburn  18191:                 ':::::&'.$path;
                   18192:     }
                   18193:     return $path;
                   18194: }
                   18195: 
1.1094    raeburn  18196: sub captcha_display {
1.1327    raeburn  18197:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18198:     my ($output,$error);
1.1234    raeburn  18199:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18200:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18201:     if ($captcha eq 'original') {
1.1094    raeburn  18202:         $output = &create_captcha();
                   18203:         unless ($output) {
1.1172    raeburn  18204:             $error = 'captcha';
1.1094    raeburn  18205:         }
                   18206:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18207:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18208:         unless ($output) {
1.1172    raeburn  18209:             $error = 'recaptcha';
1.1094    raeburn  18210:         }
                   18211:     }
1.1234    raeburn  18212:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18213: }
                   18214: 
                   18215: sub captcha_response {
1.1327    raeburn  18216:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18217:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18218:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18219:     if ($captcha eq 'original') {
1.1094    raeburn  18220:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18221:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18222:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18223:     } else {
                   18224:         $captcha_chk = 1;
                   18225:     }
                   18226:     return ($captcha_chk,$captcha_error);
                   18227: }
                   18228: 
                   18229: sub get_captcha_config {
1.1327    raeburn  18230:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18231:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18232:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18233:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18234:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18235:     if ($context eq 'usercreation') {
                   18236:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18237:         if (ref($domconfig{$context}) eq 'HASH') {
                   18238:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18239:             if (ref($hashtocheck) eq 'HASH') {
                   18240:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18241:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18242:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18243:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18244:                     }
                   18245:                     if ($privkey && $pubkey) {
                   18246:                         $captcha = 'recaptcha';
1.1234    raeburn  18247:                         $version = $hashtocheck->{'recaptchaversion'};
                   18248:                         if ($version ne '2') {
                   18249:                             $version = 1;
                   18250:                         }
1.1095    raeburn  18251:                     } else {
                   18252:                         $captcha = 'original';
                   18253:                     }
                   18254:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18255:                     $captcha = 'original';
                   18256:                 }
1.1094    raeburn  18257:             }
1.1095    raeburn  18258:         } else {
                   18259:             $captcha = 'captcha';
                   18260:         }
                   18261:     } elsif ($context eq 'login') {
                   18262:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18263:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18264:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18265:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18266:             if ($privkey && $pubkey) {
                   18267:                 $captcha = 'recaptcha';
1.1234    raeburn  18268:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18269:                 if ($version ne '2') {
                   18270:                     $version = 1; 
                   18271:                 }
1.1095    raeburn  18272:             } else {
                   18273:                 $captcha = 'original';
1.1094    raeburn  18274:             }
1.1095    raeburn  18275:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18276:             $captcha = 'original';
1.1094    raeburn  18277:         }
1.1327    raeburn  18278:     } elsif ($context eq 'passwords') {
                   18279:         if ($dom_in_effect) {
                   18280:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18281:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18282:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18283:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18284:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18285:                 }
                   18286:                 if ($privkey && $pubkey) {
                   18287:                     $captcha = 'recaptcha';
                   18288:                     $version = $passwdconf{'recaptchaversion'};
                   18289:                     if ($version ne '2') {
                   18290:                         $version = 1;
                   18291:                     }
                   18292:                 } else {
                   18293:                     $captcha = 'original';
                   18294:                 }
                   18295:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18296:                 $captcha = 'original';
                   18297:             }
                   18298:         }
                   18299:     } 
1.1234    raeburn  18300:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18301: }
                   18302: 
                   18303: sub create_captcha {
                   18304:     my %captcha_params = &captcha_settings();
                   18305:     my ($output,$maxtries,$tries) = ('',10,0);
                   18306:     while ($tries < $maxtries) {
                   18307:         $tries ++;
                   18308:         my $captcha = Authen::Captcha->new (
                   18309:                                            output_folder => $captcha_params{'output_dir'},
                   18310:                                            data_folder   => $captcha_params{'db_dir'},
                   18311:                                           );
                   18312:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18313: 
                   18314:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18315:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  18316:                       '<span class="LC_nobreak">'.
1.1094    raeburn  18317:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18318:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1367    raeburn  18319:                       '</span><br />'.
1.1176    raeburn  18320:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18321:             last;
                   18322:         }
                   18323:     }
1.1323    raeburn  18324:     if ($output eq '') {
                   18325:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18326:     }
1.1094    raeburn  18327:     return $output;
                   18328: }
                   18329: 
                   18330: sub captcha_settings {
                   18331:     my %captcha_params = (
                   18332:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18333:                            www_output_dir => "/captchaspool",
                   18334:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18335:                            numchars       => '5',
                   18336:                          );
                   18337:     return %captcha_params;
                   18338: }
                   18339: 
                   18340: sub check_captcha {
                   18341:     my ($captcha_chk,$captcha_error);
                   18342:     my $code = $env{'form.code'};
                   18343:     my $md5sum = $env{'form.crypt'};
                   18344:     my %captcha_params = &captcha_settings();
                   18345:     my $captcha = Authen::Captcha->new(
                   18346:                       output_folder => $captcha_params{'output_dir'},
                   18347:                       data_folder   => $captcha_params{'db_dir'},
                   18348:                   );
1.1109    raeburn  18349:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18350:     my %captcha_hash = (
                   18351:                         0       => 'Code not checked (file error)',
                   18352:                        -1      => 'Failed: code expired',
                   18353:                        -2      => 'Failed: invalid code (not in database)',
                   18354:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18355:     );
                   18356:     if ($captcha_chk != 1) {
                   18357:         $captcha_error = $captcha_hash{$captcha_chk}
                   18358:     }
                   18359:     return ($captcha_chk,$captcha_error);
                   18360: }
                   18361: 
                   18362: sub create_recaptcha {
1.1234    raeburn  18363:     my ($pubkey,$version) = @_;
                   18364:     if ($version >= 2) {
1.1367    raeburn  18365:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18366:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  18367:     } else {
                   18368:         my $use_ssl;
                   18369:         if ($ENV{'SERVER_PORT'} == 443) {
                   18370:             $use_ssl = 1;
                   18371:         }
                   18372:         my $captcha = Captcha::reCAPTCHA->new;
                   18373:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18374:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18375:                &mt('If the text is hard to read, [_1] will replace them.',
                   18376:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18377:                '<br /><br />';
                   18378:     }
1.1094    raeburn  18379: }
                   18380: 
                   18381: sub check_recaptcha {
1.1234    raeburn  18382:     my ($privkey,$version) = @_;
1.1094    raeburn  18383:     my $captcha_chk;
1.1350    raeburn  18384:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18385:     if ($version >= 2) {
                   18386:         my %info = (
                   18387:                      secret   => $privkey, 
                   18388:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18389:                      remoteip => $ip,
1.1234    raeburn  18390:                    );
1.1280    raeburn  18391:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18392:         $request->content(join('&',map {
                   18393:                          my $name = escape($_);
                   18394:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18395:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18396:                          : &escape($info{$_}) );
                   18397:         } keys(%info)));
                   18398:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18399:         if ($response->is_success)  {
                   18400:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18401:             if (ref($data) eq 'HASH') {
                   18402:                 if ($data->{'success'}) {
                   18403:                     $captcha_chk = 1;
                   18404:                 }
                   18405:             }
                   18406:         }
                   18407:     } else {
                   18408:         my $captcha = Captcha::reCAPTCHA->new;
                   18409:         my $captcha_result =
                   18410:             $captcha->check_answer(
                   18411:                                     $privkey,
1.1350    raeburn  18412:                                     $ip,
1.1234    raeburn  18413:                                     $env{'form.recaptcha_challenge_field'},
                   18414:                                     $env{'form.recaptcha_response_field'},
                   18415:                                   );
                   18416:         if ($captcha_result->{is_valid}) {
                   18417:             $captcha_chk = 1;
                   18418:         }
1.1094    raeburn  18419:     }
                   18420:     return $captcha_chk;
                   18421: }
                   18422: 
1.1174    raeburn  18423: sub emailusername_info {
1.1244    raeburn  18424:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18425:     my %titles = &Apache::lonlocal::texthash (
                   18426:                      lastname      => 'Last Name',
                   18427:                      firstname     => 'First Name',
                   18428:                      institution   => 'School/college/university',
                   18429:                      location      => "School's city, state/province, country",
                   18430:                      web           => "School's web address",
                   18431:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18432:                      id            => 'Student/Employee ID',
1.1174    raeburn  18433:                  );
                   18434:     return (\@fields,\%titles);
                   18435: }
                   18436: 
1.1161    raeburn  18437: sub cleanup_html {
                   18438:     my ($incoming) = @_;
                   18439:     my $outgoing;
                   18440:     if ($incoming ne '') {
                   18441:         $outgoing = $incoming;
                   18442:         $outgoing =~ s/;/&#059;/g;
                   18443:         $outgoing =~ s/\#/&#035;/g;
                   18444:         $outgoing =~ s/\&/&#038;/g;
                   18445:         $outgoing =~ s/</&#060;/g;
                   18446:         $outgoing =~ s/>/&#062;/g;
                   18447:         $outgoing =~ s/\(/&#040/g;
                   18448:         $outgoing =~ s/\)/&#041;/g;
                   18449:         $outgoing =~ s/"/&#034;/g;
                   18450:         $outgoing =~ s/'/&#039;/g;
                   18451:         $outgoing =~ s/\$/&#036;/g;
                   18452:         $outgoing =~ s{/}{&#047;}g;
                   18453:         $outgoing =~ s/=/&#061;/g;
                   18454:         $outgoing =~ s/\\/&#092;/g
                   18455:     }
                   18456:     return $outgoing;
                   18457: }
                   18458: 
1.1190    musolffc 18459: # Checks for critical messages and returns a redirect url if one exists.
                   18460: # $interval indicates how often to check for messages.
1.1282    raeburn  18461: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18462: sub critical_redirect {
1.1282    raeburn  18463:     my ($interval,$context) = @_;
1.1356    raeburn  18464:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18465:         return ();
                   18466:     }
1.1190    musolffc 18467:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18468:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18469:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18470:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18471:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   18472:             if ($blocked) {
                   18473:                 my $checkrole = "cm./$cdom/$cnum";
                   18474:                 if ($env{'request.course.sec'} ne '') {
                   18475:                     $checkrole .= "/$env{'request.course.sec'}";
                   18476:                 }
                   18477:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18478:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18479:                     return;
                   18480:                 }
                   18481:             }
                   18482:         }
1.1190    musolffc 18483:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18484:                                         $env{'user.name'});
                   18485:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18486:         my $redirecturl;
1.1190    musolffc 18487:         if ($what[0]) {
1.1356    raeburn  18488: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 18489: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18490: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18491:                 return (1, $url);
1.1190    musolffc 18492:             }
1.1191    raeburn  18493:         }
                   18494:     } 
                   18495:     return ();
1.1190    musolffc 18496: }
                   18497: 
1.1174    raeburn  18498: # Use:
                   18499: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18500: #
                   18501: ##################################################
                   18502: #          password associated functions         #
                   18503: ##################################################
                   18504: sub des_keys {
                   18505:     # Make a new key for DES encryption.
                   18506:     # Each key has two parts which are returned separately.
                   18507:     # Please note:  Each key must be passed through the &hex function
                   18508:     # before it is output to the web browser.  The hex versions cannot
                   18509:     # be used to decrypt.
                   18510:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18511:                 '8','9','a','b','c','d','e','f');
                   18512:     my $lkey='';
                   18513:     for (0..7) {
                   18514:         $lkey.=$hexstr[rand(15)];
                   18515:     }
                   18516:     my $ukey='';
                   18517:     for (0..7) {
                   18518:         $ukey.=$hexstr[rand(15)];
                   18519:     }
                   18520:     return ($lkey,$ukey);
                   18521: }
                   18522: 
                   18523: sub des_decrypt {
                   18524:     my ($key,$cyphertext) = @_;
                   18525:     my $keybin=pack("H16",$key);
                   18526:     my $cypher;
                   18527:     if ($Crypt::DES::VERSION>=2.03) {
                   18528:         $cypher=new Crypt::DES $keybin;
                   18529:     } else {
                   18530:         $cypher=new DES $keybin;
                   18531:     }
1.1233    raeburn  18532:     my $plaintext='';
                   18533:     my $cypherlength = length($cyphertext);
                   18534:     my $numchunks = int($cypherlength/32);
                   18535:     for (my $j=0; $j<$numchunks; $j++) {
                   18536:         my $start = $j*32;
                   18537:         my $cypherblock = substr($cyphertext,$start,32);
                   18538:         my $chunk =
                   18539:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18540:         $chunk .=
                   18541:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18542:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18543:         $plaintext .= $chunk;
                   18544:     }
1.1174    raeburn  18545:     return $plaintext;
                   18546: }
                   18547: 
1.1344    raeburn  18548: sub get_requested_shorturls {
1.1309    raeburn  18549:     my ($cdom,$cnum,$navmap) = @_;
                   18550:     return unless (ref($navmap));
1.1344    raeburn  18551:     my ($numnew,$errors);
1.1309    raeburn  18552:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18553:     if (@toshorten) {
                   18554:         my (%maps,%resources,%titles);
                   18555:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18556:                                                                'shorturls',$cdom,$cnum);
                   18557:         if (keys(%resources)) {
1.1344    raeburn  18558:             my %tocreate;
1.1309    raeburn  18559:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18560:                 my $symb = $resources{$item};
                   18561:                 if ($symb) {
                   18562:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18563:                 }
                   18564:             }
1.1344    raeburn  18565:             if (keys(%tocreate)) {
                   18566:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18567:                                                       \%tocreate);
                   18568:             }
1.1309    raeburn  18569:         }
1.1344    raeburn  18570:     }
                   18571:     return ($numnew,$errors);
                   18572: }
                   18573: 
                   18574: sub make_short_symbs {
                   18575:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18576:     my ($numnew,@errors);
                   18577:     if (ref($tocreateref) eq 'HASH') {
                   18578:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18579:         if (keys(%tocreate)) {
                   18580:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18581:             my $su = Short::URL->new(no_vowels => 1);
                   18582:             my $init = '';
                   18583:             my (%newunique,%addcourse,%courseonly,%failed);
                   18584:             # get lock on tiny db
                   18585:             my $now = time;
1.1344    raeburn  18586:             if ($lockuser eq '') {
                   18587:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18588:             }
1.1309    raeburn  18589:             my $lockhash = {
1.1344    raeburn  18590:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18591:                             };
                   18592:             my $tries = 0;
                   18593:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18594:             my ($code,$error);
                   18595:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18596:                 $tries ++;
                   18597:                 sleep 1;
1.1319    raeburn  18598:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18599:             }
                   18600:             if ($gotlock eq 'ok') {
                   18601:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18602:                                        \%addcourse,\%courseonly,\%failed);
                   18603:                 if (keys(%failed)) {
                   18604:                     my $numfailed = scalar(keys(%failed));
                   18605:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18606:                 }
                   18607:                 if (keys(%newunique)) {
                   18608:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18609:                     if ($putres eq 'ok') {
                   18610:                         $numnew = scalar(keys(%newunique));
                   18611:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18612:                         unless ($newputres eq 'ok') {
                   18613:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18614:                         }
                   18615:                     } else {
                   18616:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18617:                     }
                   18618:                 }
                   18619:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18620:                 unless ($dellockres eq 'ok') {
                   18621:                     push(@errors,&mt('error: could not release lockfile'));
                   18622:                 }
                   18623:             } else {
                   18624:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18625:             }
                   18626:             if (keys(%courseonly)) {
                   18627:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18628:                 if ($result ne 'ok') {
                   18629:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18630:                 }
                   18631:             }
                   18632:         }
                   18633:     }
                   18634:     return ($numnew,\@errors);
                   18635: }
                   18636: 
                   18637: sub shorten_symbs {
                   18638:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18639:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18640:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18641:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18642:     my (%possibles,%collisions);
                   18643:     foreach my $key (keys(%{$tocreate})) {
                   18644:         my $num = String::CRC32::crc32($key);
                   18645:         my $tiny = $su->encode($num,$init);
                   18646:         if ($tiny) {
                   18647:             $possibles{$tiny} = $key;
                   18648:         }
                   18649:     }
                   18650:     if (!$init) {
                   18651:         $init = 1;
                   18652:     } else {
                   18653:         $init ++;
                   18654:     }
                   18655:     if (keys(%possibles)) {
                   18656:         my @posstiny = keys(%possibles);
                   18657:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18658:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18659:         if (keys(%currtiny)) {
                   18660:             foreach my $key (keys(%currtiny)) {
                   18661:                 next if ($currtiny{$key} eq '');
                   18662:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18663:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18664:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18665:                         $courseonly->{$tsymb} = $key;
                   18666:                     }
                   18667:                 } else {
                   18668:                     $collisions{$possibles{$key}} = 1;
                   18669:                 }
                   18670:                 delete($possibles{$key});
                   18671:             }
                   18672:         }
                   18673:         foreach my $key (keys(%possibles)) {
                   18674:             $newunique->{$key} = $possibles{$key};
                   18675:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18676:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18677:                 $addcourse->{$tsymb} = $key;
                   18678:             }
                   18679:         }
                   18680:     }
                   18681:     if (keys(%collisions)) {
                   18682:         if ($init <5) {
                   18683:             if (!$init) {
                   18684:                 $init = 1;
                   18685:             } else {
                   18686:                 $init ++;
                   18687:             }
                   18688:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18689:                                    $newunique,$addcourse,$courseonly,$failed);
                   18690:         } else {
                   18691:             foreach my $key (keys(%collisions)) {
                   18692:                 $failed->{$key} = 1;
                   18693:             }
                   18694:         }
                   18695:     }
                   18696:     return $init;
                   18697: }
                   18698: 
1.1328    raeburn  18699: sub is_nonframeable {
1.1329    raeburn  18700:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18701:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18702:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18703: 
                   18704:     $remprotocol = lc($remprotocol);
                   18705:     $remhost = lc($remhost);
                   18706:     my $remport = 80;
                   18707:     if ($remprotocol eq 'https') {
                   18708:         $remport = 443;
                   18709:     }
1.1330    raeburn  18710:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18711:     if ($cached) {
                   18712:         unless ($nocache) {
                   18713:             if ($result) {
                   18714:                 return 1;
                   18715:             } else {
                   18716:                 return 0;
                   18717:             }
                   18718:         }
                   18719:     }
1.1328    raeburn  18720:     my $uselink;
                   18721:     my $request = new HTTP::Request('HEAD',$url);
                   18722:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18723:     if ($response->is_success()) {
                   18724:         my $secpolicy = lc($response->header('content-security-policy'));
                   18725:         my $xframeop = lc($response->header('x-frame-options'));
                   18726:         $secpolicy =~ s/^\s+|\s+$//g;
                   18727:         $xframeop =~ s/^\s+|\s+$//g;
                   18728:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18729:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18730:             my ($origin,$protocol,$port);
                   18731:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18732:                 $port = $ENV{'SERVER_PORT'};
                   18733:             } else {
                   18734:                 $port = 80;
                   18735:             }
                   18736:             if ($absolute eq '') {
                   18737:                 $protocol = 'http:';
                   18738:                 if ($port == 443) {
                   18739:                     $protocol = 'https:';
                   18740:                 }
                   18741:                 $origin = $protocol.'//'.lc($hostname);
                   18742:             } else {
                   18743:                 $origin = lc($absolute);
                   18744:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18745:             }
                   18746:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18747:                 my $framepolicy = $1;
                   18748:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18749:                 my @policies = split(/\s+/,$framepolicy);
                   18750:                 if (@policies) {
                   18751:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18752:                         $uselink = 1;
                   18753:                     } else {
                   18754:                         $uselink = 1;
                   18755:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18756:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18757:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18758:                             undef($uselink);
                   18759:                         }
                   18760:                         if ($uselink) {
                   18761:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18762:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18763:                                     undef($uselink);
                   18764:                                 }
                   18765:                             }
                   18766:                         }
                   18767:                         if ($uselink) {
                   18768:                             my @possok;
                   18769:                             if ($ip ne '') {
                   18770:                                 push(@possok,$ip);
                   18771:                             }
                   18772:                             my $hoststr = '';
                   18773:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18774:                                 if ($hoststr eq '') {
                   18775:                                     $hoststr = $part;
                   18776:                                 } else {
                   18777:                                     $hoststr = "$part.$hoststr";
                   18778:                                 }
                   18779:                                 if ($hoststr eq $hostname) {
                   18780:                                     push(@possok,$hostname);
                   18781:                                 } else {
                   18782:                                     push(@possok,"*.$hoststr");
                   18783:                                 }
                   18784:                             }
                   18785:                             if (@possok) {
                   18786:                                 foreach my $poss (@possok) {
                   18787:                                     last if (!$uselink);
                   18788:                                     foreach my $policy (@policies) {
                   18789:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18790:                                             undef($uselink);
                   18791:                                             last;
                   18792:                                         }
                   18793:                                     }
                   18794:                                 }
                   18795:                             }
                   18796:                         }
                   18797:                     }
                   18798:                 }
                   18799:             } elsif ($xframeop ne '') {
                   18800:                 $uselink = 1;
                   18801:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18802:                 if (@policies) {
                   18803:                     unless (grep(/^deny$/,@policies)) {
                   18804:                         if ($origin ne '') {
                   18805:                             if (grep(/^sameorigin$/,@policies)) {
                   18806:                                 if ($remotehost eq $origin) {
                   18807:                                     undef($uselink);
                   18808:                                 }
                   18809:                             }
                   18810:                             if ($uselink) {
                   18811:                                 foreach my $policy (@policies) {
                   18812:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18813:                                         my $allowfrom = $1;
                   18814:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18815:                                             undef($uselink);
                   18816:                                             last;
                   18817:                                         }
                   18818:                                     }
                   18819:                                 }
                   18820:                             }
                   18821:                         }
                   18822:                     }
                   18823:                 }
                   18824:             }
                   18825:         }
                   18826:     }
1.1329    raeburn  18827:     if ($nocache) {
                   18828:         if ($cached) {
                   18829:             my $devalidate;
                   18830:             if ($uselink && !$result) {
                   18831:                 $devalidate = 1;
                   18832:             } elsif (!$uselink && $result) {
                   18833:                 $devalidate = 1;
                   18834:             }
                   18835:             if ($devalidate) {
                   18836:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18837:             }
                   18838:         }
                   18839:     } else {
                   18840:         if ($uselink) {
                   18841:             $result = 1;
                   18842:         } else {
                   18843:             $result = 0;
                   18844:         }
                   18845:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18846:     }
1.1328    raeburn  18847:     return $uselink;
                   18848: }
                   18849: 
1.1359    raeburn  18850: sub page_menu {
                   18851:     my ($menucolls,$menunum) = @_;
                   18852:     my %menu;
                   18853:     foreach my $item (split(/;/,$menucolls)) {
                   18854:         my ($num,$value) = split(/\%/,$item);
                   18855:         if ($num eq $menunum) {
                   18856:             my @entries = split(/\&/,$value);
                   18857:             foreach my $entry (@entries) {
                   18858:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  18859:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  18860:                     $menu{$name} = $fields;
                   18861:                 } else {
                   18862:                     my @shown;
                   18863:                     if ($fields =~ /,/) {
                   18864:                         @shown = split(/,/,$fields);
                   18865:                     } else {
                   18866:                         @shown = ($fields);
                   18867:                     }
                   18868:                     if (@shown) {
                   18869:                         foreach my $field (@shown) {
                   18870:                             next if ($field eq '');
                   18871:                             $menu{$field} = 1;
                   18872:                         }
                   18873:                     }
                   18874:                 }
                   18875:             }
                   18876:         }
                   18877:     }
                   18878:     return %menu;
                   18879: }
                   18880: 
1.112     bowersj2 18881: 1;
                   18882: __END__;
1.41      ng       18883: 

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